Question

I'm trying to write a script that will take input from a .txt file of IP address. Do a reverse DNS lookup to get the hostname of the IP address and then export that data into .csv file.

Here is what I have so far.

# getting the IP's from the file


$IPADDR = Get-Content "C:\Users\douglasfrancis\Desktop\IP_Test.txt"


ForEach ($IPADDR in $IPADDR)
{
  [System.Net.DNS]::GetHostbyAddress($IPADDR) | Add-Member -Name IP -Value $IPADDR -    MemberType NoteProperty -PassThru | select IP, HostName | sort -property Hostname | export-    csv "C:\Users\douglasfrancis\Desktop\ReverseLookup.csv" 

}

How it is now the created CSV file will have the column heads that I assigned and the last IP address in the list with its hostname. So somehow its dropping everything else.

If I run it with the export-csv commented out then all the IP's are displayed in the console but are not sorted by hostname.

I've used this same basic pipe before with no issues so I'm kinda at a loss for what is going on here. Any help would be awesome.

Thanks,

Was it helpful?

Solution

You should put the result in an array before exporting it to CSV :

# getting the IP's from the file

$IPADDRS = Get-Content "C:\Users\douglasfrancis\Desktop\IP_Test.txt"

$result = @()
ForEach ($IPADDR in $IPADDRS)
{
  $result += [System.Net.DNS]::GetHostbyAddress($IPADDR) | Add-Member -Name IP -Value $IPADDR -MemberType NoteProperty -PassThru | select IP, HostName
}
$result  | sort -property Hostname | export-csv "C:\Users\douglasfrancis\Desktop\ReverseLookup.csv" -NoTypeInformation

@David Braban is true, this was not your trouble but I use $IPADDRS for the collection and $IPADDR for each value, this way it's much correct (en readable)/

OTHER TIPS

In your code, I see:

ForEach ($IPADDR in $IPADDR)

That's very wrong: you use the same variable both as your collection and as the variable to iterate.

Use:

$ipaddr | %{ [System.Net.DNS]::GetHostbyAddress($_) } | ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top