NSlookup in PowerShell

nslookup.exe is a command line executable that is used to discover the IP address of a remote machine from its FQDN. The results look something like this:

PS> nslookup powershell.org
DNS request timed out.
    timeout was 2 seconds.
Server:  UnKnown

Non-authoritative answer:
DNS request timed out.
    timeout was 2 seconds.
Name:    powershell.org

The output is text – not the most useful of things to use.

One option if you want to perform lookups in PowerShell is to write your self a script

$ns = (nslookup.exe powershell.org )[-4..-3]
$lookup = [PSCustomObject]@{
  Name = ($ns[0] -split ‘:’)[1].Trim()
  Address = ($ns[1] -split ‘:’)[1].Trim()

Run nslookup and take the 3rd and 4th lines from the end of the output. Then create an output object where the text in the array is split at the : the second element is used and trimmed of blank spaces.

If you like using .NET static methods you can do this:

PS> [System.Net.DNS]::GetHostEntry(‘powershell.org’)

HostName       Aliases AddressList
——–       ——- ———–
powershell.org {}      {,}

Best of all is the use the Resolve-DnsName cmdlet from the DnsClient module that’s present in Windows 8 and later

PS> Resolve-DnsName -Name ‘powershell.org’ | ft -a

Name           Type TTL Section IPAddress
—-           —- — ——- ———
powershell.org A    300 Answer

This entry was posted in DNS, Powershell. Bookmark the permalink.

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