7

When I run nslookup from a PowerShell script, I always get an error (which is output to the console) despite the fact the lookup succeeds:

PS C:\Windows\system32> $MyOutput = nslookup -q=SOA superuser.com
8.8.4.4 nslookup : Non-authoritative answer: At line:1 char:13
+ $MyOutput = nslookup -q=SOA superuser.com 8.8.4.4
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Non-authoritative answer::String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

This seems to be caused by the fact the answer is non-authoritative. Doing a lookup against an authoritative DNS server doesn't return an error.

In my attempts to find a solution myself, I found this SO answer. It suggests using the Resolve-DNSName command. Unfortunately that requires Windows 8.1/Server 2012 R2 and some of the systems my script will run on are Windows 7-era.

How can I prevent this error from being displayed?

Bonus points for explaining why PowerShell thinks an error has occurred!

1 Answers1

4

Ignore the executable's error by redirecting to $null

Your executable is sending output to the STDERR stream. You can suppress it by redirecting it to the automatic $null variable:

nslookup.exe example.com 2>$null

Notes:

  • You must redirect to PowerShell's $null variable. PS won't let you do it the old school way (i.e. 2>nul).

  • Redirecting to $null is faster than using Out-Null


Explanation

NSLookup is sending a portion of its output to the STDERR stream. Whenever a Windows console application does this, PowerShell reports this as a NativeCommandError error.

In Command Prompt run nslookup -q=SOA superuser.com 1>nul 2>con to see what NSLookup is writing to STDERR:

Non-authoritative answer:

This is exactly what PowerShell returns in the first line of its error message:

nslookup : Non-authoritative answer:
At line:1 char:1
+ nslookup -q=ns example.com

Apparently NSLookup returns an error when its answer includes records from a non-authoritative name server. However in your case that doesn't seem to be a problem so you can ignore the error as described above.