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

I want to run nslookup in a powershell script by assigning the output to a string variable that I can parse. I don’t want to see the echo like “Unauthorized answer:” in the powershell window from CMD execution, but everything that I tried to pass or redirect the output of the command exclusively to the variable did not work or did not break the variable.

Example:

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

I tried several workarounds ...

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 is a better way to do this. The way I work with the string here to get the IP address is a few more lines than I would 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

, , , nslookup, , powershell Resolve-DnsName. , , IP-. , , (invoke-WebRequest ifconfig.me/ip).Content script.

+4
1

, -Server Resolve-DnsName.

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

MSDN Resolve-DnsName:

-Server < String [] >
  IP- DNS-, . DNS- , .

+4

Source: https://habr.com/ru/post/1605924/


All Articles