How can I look up IP addresses for hundreds of hostnames in PowerShell?

0
1
Asked By MellowCedar42 On

I have a list of roughly 740 devices where I only know the hostnames. Is there a PowerShell script that can resolve each hostname to its IP address in bulk and save the results, ideally to a CSV file?

3 Answers

Answered By CopperWillow56 On

For a list this large, PowerShell 7's parallel processing is worth considering. For example:

Get-Content "C:Temphostnames.txt" | ForEach-Object -Parallel {
Resolve-DnsName -Name $_ -Type A -ErrorAction SilentlyContinue
} -ThrottleLimit 50

You would still want to wrap the output in custom objects and export it to CSV, but limiting concurrency helps avoid overwhelming the DNS server.

Answered By SilverOrbit31 On

You can also use the .NET DNS method if you want a simple alternative:

$hostnames = Get-Content "C:Temphostnames.txt"

$results = foreach ($hostname in $hostnames) {
$name = $hostname.Trim()
try {
$ips = [System.Net.Dns]::GetHostAddresses($name) |
ForEach-Object IPAddressToString

[PSCustomObject]@{
HostName = $name
IPAddress = $ips -join '; '
}
}
catch {
[PSCustomObject]@{
HostName = $name
IPAddress = 'Not Found'
}
}
}

$results | Export-Csv "C:Temphostnames_with_ips.csv" -NoTypeInformation

Answered By BrightFalcon7 On

In PowerShell, Resolve-DnsName is usually cleaner than parsing nslookup output because it returns structured objects. Read the hostnames from a text file, resolve the A records, handle failures, and export everything to CSV:

$hostnames = Get-Content "C:Temphosts.txt"

$results = foreach ($hostname in $hostnames) {
$name = $hostname.Trim()
try {
$ips = Resolve-DnsName -Name $name -Type A -ErrorAction Stop |
Where-Object Type -eq 'A' |
Select-Object -ExpandProperty IPAddress

[PSCustomObject]@{
HostName = $name
IPAddress = $ips -join ', '
}
}
catch {
[PSCustomObject]@{
HostName = $name
IPAddress = 'Not Found'
}
}
}

$results | Export-Csv "C:TempHostIPs.csv" -NoTypeInformation

QuickMaple19 -

For several hundred systems, this sequential version may take a while, but it is straightforward and makes the failures easy to review.

NimbleQuartz8 -

If you are using PowerShell 7, ForEach-Object -Parallel with a reasonable ThrottleLimit can speed up the lookups. Be careful not to create too many simultaneous DNS requests.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.