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

标签 powershell redirect cmd ip nslookup

我想在 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/

相关文章:

Powershell 多个 StartsWith 子句

powershell - 结合powershell输出

通过 Apache-Redirect 代理进行 Node.js Passport 身份验证

redirect - Magento:扩展客户帐户 Controller 以向忘记密码步骤添加操作

session - Internet Explorer 中的 Codeigniter 登录、 session 和重定向问题?

windows - 删除空行

windows - 如何在控制台窗口中输出窗口标题列表?

c# - 从 C# 控制台应用程序运行 CMD?

powershell - 在 Azure-Pipelines.yml 中使用 AzureFileCopy 任务输出

powershell - 如何从 PsList 传输 'Elapsed Time'(或其他输出)