문제

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,

도움이 되었습니까?

해결책

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)/

다른 팁

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($_) } | ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top