Monthly Archive

Categories

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
Address:  192.168.0.1

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

 

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()
}
$lookup

 

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 {}      {104.28.15.25, 104.28.14.25}

 

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  104.28.15.25

Comments are closed.