.Net

Quick and easy way to resolve multiple hostnames from IP addresses using PowerShell

This time we will solve simple administrator task – we have a list of IP addresses, where we have to resolve the corresponding host names.

Very simple, you may say: I will open the command prompt and will “ping -a” or will “nslookup” it. But what will you do, if you have to resolve bulk list of hundreds, sometimes thousands IP addresses?

Let’s write a short PowerShell code! Before jumping in, to accomplish this task we will prepare simple CSV file. Simplest way to accomplish this is to create Excel table. The file will include two columns: IP and HostName. The IP column will include the addresses, the HostName column will be blank at this time (see example):

IP HostName
10.10.1.2
10.10.1.3
10.10.1.4
10.10.1.15
10.10.1.16
10.10.1.17
10.10.1.18
10.10.1.19

Save the table as “CSV (comma delimited)”. In the example, the file will be located at "C:\Temp\ips.csv".

First step will be the import of the file (the table) into the variable $ips:

$ips = Import-Csv "C:\Temp\ips.csv"

This variable is very handy. It is an array, where each member represents one line from the table, we created above, with both “fields” from the table.

Next, we will build a loop, that will go through each line of the imported file:

for ($i = 0; $i -lt $ips.Count; $i++)
{
... code goes here ...
}

For each IP, we will resolve the host name. The most convenient way for this, to implement .Net.Dns class:

$result = [System.Net.Dns]::GetHostByAddress($ips[$i].IP)

A little trick, showed below, will avoid unwanted errors to be displayed on the console:

$currentEAP = $ErrorActionPreference
$ErrorActionPreference = "silentlycontinue"
... code with possible errors ...
$ErrorActionPreference = $currentEAP

Finally, we have all needed to build the script together:

$ips = Import-Csv "C:\Temp\ips.csv"
for ($i = 0; $i -lt $ips.Count; $i++)
{
$result = $null
$currentEAP = $ErrorActionPreference
$ErrorActionPreference = "silentlycontinue"
$result = [System.Net.Dns]::GetHostByAddress($ips[$i].IP)
$ErrorActionPreference = $currentEAP
if ($result)
{
$ips[$i].HostName = [string]$result.HostName
}
Write-host $ips[$i].IP","$ips[$i].HostName
}
$ips | Export-Csv "C:\Temp\ips.csv"

You can pay attention to the last line of the code. This line exports (overwrites) the file with the final data. Now you can open the same file in Excel and enjoy the view of next:

IP HostName
10.10.1.2 host1.local
10.10.1.3 host2.local
10.10.1.4 hosttest.local
10.10.1.15 srv1.local
10.10.1.16 client1.local
10.10.1.17 printer
10.10.1.18 scanner
10.10.1.19 client2.local

You may find extra line or two in the beginning of the .CSV. This data is automatically appended by PowerShell Export-Csv cmdlet. Just omit it.

Enjoy! Do not hesitate to comment.