Lange's Tech Musings

Thoughts, Problems and Solutions

PowerShell: IP and Host Name Lookups (nslookup)

Posted by Daniel Lange on 26 April 2010

When generating reports for servers, I frequently find myself needing to either find the host name of a machine from its IP or the IP from its host name. I could not find a native cmdlet to achieve this, so I began poking around MSDN and came across the DNS class in the System.Net namespace for .NET.

To lookup the IP based on hostname, try the following:

$ServerName = "WindowsPC"

[System.Net.Dns]::GetHostAddresses($ServerName)

To do a reverse lookup from the IP to a hostname, try the following:

$IP = “192.168.0.1”

[System.Net.Dns]::GetHostEntry($IP)

It is worth noting that the GetHostEntry method will work with either an IP address or a host name.  The information returned by GetHostAddress is slightly different from that returned by GetHostEntry. It is worth taking a look at both to see which will work best for you.

for more information on System.Net.DNS, take a look at the MSDN page: http://msdn.microsoft.com/en-us/library/b8hth2dy(v=VS.100).aspx

 

~Daniel

About these ads

7 Responses to “PowerShell: IP and Host Name Lookups (nslookup)”

  1. Network Unidentified…

    [...]PowerShell: IP and Host Name Lookups (nslookup) « Lange's Tech Musings[...]…

  2. Anshuman said

    How will i do it for 200 IP’s at once..? and can i populate them to a spreadsheet of excel..?

    • Since DNS is relatively quick and 200 isn’t a huge number of addresses, a simple foreach loop would get the job done. You could either use an Excel spreadsheet (see other posts I’ve made about working with Excel in PoSH) or create an array and use export-csv to save the results. If you use the array, you may want to create a custom object to store just the name and IP.

  3. What command we use to find the hostname in PowerShell?

    • If you mean the hostname of the machine you are on, $Env:Computername should work.
      If you want to get the hostname from the IP, you can use:
      $IP = “192.168.0.1”
      [System.Net.Dns]::GetHostEntry($IP).hostname

  4. cetanuVasili said

    $List_of_ips = @(“1.1.1.1″
    “2.2.2.2″
    “3.3.3.3″
    “4.4.4.4″)

    foreach ($address in $List_of_ips) {
    $hostnames += [System.Net.Dns]::GetHostEntry($address) | % {$_.HostName}
    }
    write-host $hostnames

    Amirite?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: