我正在尝试远程运行一个脚本,该脚本将使用 Powershell 中的 PsExec 双重检查 IP 地址是否正确。问题是我只希望它返回结果 True 或 False,而不在 Powershell 中显示任何其他行。
我也尝试过运行后台作业,但似乎没有成功,因为当我这样做时,它根本没有给我带来任何好处。
function remoteIPTest($Computer) {
$result = & cmd /c PsExec64.exe \\$Computer -s cmd /c "ipconfig"
if ($result -like "*10.218.5.202*") {
return "True"
}
}
$Computer = "MUC-1800035974"
remoteIPTest $Computer
运行后,我只希望应用程序返回:
True
而不是返回:
Starting cmd on MUC-1800035974... MUC-1800035974...
cmd exited on MUC-1800035974 with error code 0.
True
最佳答案
psexec
将其状态消息打印到 stderr,其中是变量赋值,例如 $result =
不捕获,因此这些消息仍然打印到屏幕上。
变量赋值仅捕获来自外部程序(例如 psexec
)的stdout输出,在本例中为 ipconfig
的输出。
因此,答案是抑制stderr,您可以使用2>$null
来做到这一点( 2
是 PowerShell 错误流的数量,stderr 映射到) - 请参阅 Redirecting Error/Output to NULL .
请注意,这也会抑制真正的错误消息。
此外,cmd /c
不需要调用,因为您可以使用 psexec
如果您正确配置了路径,则可以直接调用其他程序。
而不是这个:
$result = & cmd /c PsExec64.exe \\$Computer -s cmd /c "ipconfig"
这样做:
$result = PsExec64.exe \\$Computer -s ipconfig 2>$null
希望有帮助。
关于powershell - 尝试远程使用 PsTools (PsExec) 在 Powershell 上返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54449931/