Powershell:如何在分配变量时摆脱 CMD 输出(nslookup)

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

我想 运行 在 powershell 脚本中进行 nslookup,将输出分配给我可以解析的字符串变量。我不想在 CMD 执行的 powershell window 中看到像 "Non-authoritative answer:" 这样的回声,但是我尝试将命令的输出通过管道传输或重定向到变量的所有内容都没有工作或损坏变量。

示例:

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

我尝试了几种解决方法...

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"

也许有更好的方法来做到这一点。我在这里使用字符串获取 IP 地址的方式比我想要的要多几行。

$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 命令。我需要两台服务器,因为我正在重定向查找以获取我的 public IP。还有其他方法可以做到这一点,但这个方法非常有效,(invoke-WebRequest ifconfig.me/ip).Content 在处理这个脚本时出现了故障。

您可以通过指定 Resolve-DnsName-Server 参数来指定服务器来解析您的查询。

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

来自 MSDN documentationResolve-DnsName 命令:

-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.