How can I look up IP addresses for hundreds of hostnames in PowerShell?
Asked by
MellowCedar42
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?
Answers
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
Reply to this answer
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
Reply to this answer
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.
Reply to this answer
Add your answer
Answers are reviewed before publication.
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.