我想在 powershell 脚本中运行 nslookup,将输出分配给我可以解析的字符串变量。我不想在 CMD 执行的 powershell 窗口中看到类似“非权威答案:”的回声,但是我尝试将命令的输出专门通过管道或重定向到变量的所有操作都不起作用或破坏了变量.
示例:
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 documentation对于 Resolve-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.
关于Powershell:如何在分配变量时摆脱 CMD 输出(nslookup),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32395892/