PowerShell 中的 NSLookup 总是抛出 RemoteException 错误

I s*_*ica 5 powershell nslookup

当我nslookup从 PowerShell 脚本运行时,尽管查找成功,但我总是收到错误(输出到控制台):

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
Run Code Online (Sandbox Code Playgroud)

这似乎是由于答案不具有权威性造成的。对权威 DNS 服务器进行查找不会返回错误。

在我自己寻找解决方案的尝试中,我找到了这个SO answer。它建议使用Resolve-DNSName命令。不幸的是,这需要 Windows 8.1/Server 2012 R2 并且我的脚本将运行的一些系统是 Windows 7 时代。

如何防止显示此错误?

用于解释 PowerShell 认为发生错误的原因的奖励积分!

I s*_*ica 4

通过重定向到 $null 忽略可执行文件的错误

您的可执行文件正在将输出发送到 STDERR 流。 您可以通过将其重定向到自动 $null 变量来抑制它:

nslookup.exe example.com 2>$null
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 您必须重定向到 PowerShell 的$null变量。PS 不会让你用老派的方式来做(即2>nul)。

  • 重定向到比使用$null 更快Out-Null


解释

NSLookup 正在将其输出的一部分发送到STDERR 流。每当 Windows 控制台应用程序执行此操作时,PowerShell 都会将此报告为NativeCommandError错误。

在命令提示符下运行nslookup -q=SOA superuser.com 1>nul 2>con以查看 NSLookup 正在写入 STDERR 的内容:

非权威答案:

这正是PowerShell在其错误消息的第一行中返回的内容:

nslookup :非权威答案:
在 line:1 char:1
+ nslookup -q=ns example.com

显然,当 NSLookup 的答案包含来自非权威名称服务器的记录时,它会返回错误。但是,在您的情况下,这似乎不是问题,因此您可以忽略上述错误。