Search code examples
powershellhttp-redirectcmdipnslookup

Powershell: how to get rid of CMD output while assigning a variable (nslookup)


I want to run nslookup in a powershell script, assigning the output to a string variable I can parse up. I don't want to see echos like "Non-authoritative answer:" in the powershell window from the CMD execution, but everything I have tried to pipe or redirect the output of the command exclusively to the variable have not worked or broken the variable.

Example:

PS> $temp = (& nslookup 'myip.opendns.com','resolver1.opendns.com');
Non-authoritative answer:

I've tried several work-arounds...

PS> $temp = Invoke-Expression "cmd /c nslookup myip.opendns.com resolver1.opendns.com" >$null

PS> $temp = Invoke-Expression "cmd /c @ECHO off && nslookup myip.opendns.com resolver1.opendns.com"

Maybe there's a better way to do this. The way I'm working with a string here just to get the IP address is a few more lines than I'd like.

$temp = (nslookup myip.opendns.com resolver1.opendns.com) | Out-String
$temp = $temp.split()
$tempIPs = $temp -match "^(.|\r|\n)*?\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b"
$publicIP = $tempIPs[1]
return $PublicIP

I've gone this route because using two servers, like I'm doing with nslookup, doesn't seem to work with powershell's Resolve-DnsName command. I need the two servers because I'm redirecting the lookup to get my public IP. There are other ways to do that, but this one works really well and (invoke-WebRequest ifconfig.me/ip).Content has glitched out on me while working on this script.


Solution

  • You can specify the server to resolve your query against by specifying the -Server parameter of Resolve-DnsName.

    Resolve-DnsName -Name myip.opendns.com -Server resolver1.opendns.com
    

    From the MSDN documentation for the Resolve-DnsName command:

    -Server <String[]>
        Specifies the IP addresses or host names of the DNS servers to be queried. By default the interface DNS servers are queried if this parameter is not supplied.