Reputation: 33
Complete powershell noob here. I am attempting to do the following:
I was attempting to use the following script however I do not know what IP address is which since there are some errors:
get-content .\dnsip.txt | ForEach-Object {([system.net.dns]::GetHostByAddress($_)).hostname
Can someone help me write a script that would do this?
Thanks!
Upvotes: 2
Views: 5854
Reputation: 25001
You can do the following:
Get-Content .\dnsip.txt | ForEach-Object {
$obj = "" | Select-Object IPAddress,Hostname
try {
$obj.Hostname = ([system.net.dns]::GetHostByAddress($_)).hostname
} catch {
$obj.Hostname = 'Unknown Host'
}
$obj.IPAddress = $_
$obj
} | Export-Csv -Path Output.csv -NoType
Explanation:
During each iteration, a new object $obj
is created with two properties, IPAddress
and Hostname
, set as empty strings. A try {}
block is used to attempt to retrieve the Hostname
value using your method. If it succeeds, Hostname
will be assigned the value returned by the command. If that throws an exception, it will be caught by the catch {}
block. In side catch {}
, the Hostname
property is given a value of Unknown Host
. Then IPAddress
is assigned the current item processed ($_
) from your Get-Content
.
All custom objects are exported to Output.csv
via Export-Csv
. The -NoType
switch prevents data type information from being printed at the top of the CSV file.
Upvotes: 4