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

Question:

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:

I’ve tried several work-arounds…

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.

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.

Answer:

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

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.

Source:

Powershell: how to get rid of CMD output while assigning a variable (nslookup) by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply