I got this script from online. Figured at the very least I could figure out how to export the data to a CSV. This has proven to be so far past my ability. I've tried Export-Csv
and pipe, but neither have had success.
I had one successful attempt but all the data got shoved into 1 column and cut off, the -Width
parameter didn't resolve that either. The rest of the time I just get random information like Length
or what appears to be corrupted data with number and letters jumbled up.
All this script does it run ping
and nslookup
on a list of IPs. I want to move it to a CSV file so I can sort the data and find IP's that are empty/not being used anymore to clean up our IP space or even identify problems in our DNS.
$InputFile = 'C:\Temp\list.txt'
$addresses = Get-Content $InputFile
$reader = New-Object IO.StreamReader $InputFile
while ($reader.ReadLine() -ne $null) { $TotalIPs++ }
Write-Host ""
Write-Host "Performing nslookup on each address..."
foreach ($address in $addresses) {
## Progress bar
$i++
$percentdone = (($i / $TotalIPs) * 100)
$percentdonerounded = "{0:N0}" -f $percentdone
Write-Progress -Activity "Performing nslookups" -CurrentOperation "Working on IP: $address (IP $i of $TotalIPs)" -Status "$percentdonerounded% complete" -PercentComplete $percentdone
## End progress bar
try {
[System.Net.Dns]::Resolve($address) | Select HostName, AddressList
} catch {
Write-Host "$address was not found. $_" -ForegroundColor Green
}
}
Write-Host ""
Write-Host "Pinging each address..."
foreach($address in $addresses) {
## Progress bar
$j++
$percentdone2 = (($j / $TotalIPs) * 100)
$percentdonerounded2 = "{0:N0}" -f $percentdone2
Write-Progress -Activity "Performing pings" -CurrentOperation "Pinging IP: $address (IP $j of $TotalIPs)" -Status "$percentdonerounded2% complete" -PercentComplete $percentdone2
## End progress bar
if (Test-Connection -ComputerName $address -Count 2 -Quiet) {
Write-Host "$address responded" -ForegroundColor Green
} else {
Write-Warning "$address does not respond to pings"
}
}
Write-Host ""
Write-Host "Done!"
Simplify, simplify ...
Get-Content $InputFile | ForEach-Object {
$ip = $_
try {
$dns = [Net.Dns]::Resolve($ip)
} catch {
Write-Host "$address not found.`n$_"
}
New-Object -Type PSObject -Property @{
'Address' = $ip
'Hostname' = $dns.Hostname
'AddressList' = $dns.AddressList
'Online' = [bool](Test-Connection $ip -Count 2 -Quiet)
}
} | Export-Csv 'C:\path\to\output.csv' -NoType