powershell - 尝试远程使用 PsTools (PsExec) 在 Powershell 上返回结果

标签 powershell psexec

我正在尝试远程运行一个脚本,该脚本将使用 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/

相关文章:

shell - psexec 针对 Windows 10 远程目标失败

java - 在java中使用PsExec.exe

c++ - 程序的本地执行不需要回车。远程执行呢?

regex - 如何删除字符串中的多个字符

powershell - 从GUID列表中获取GetADUser

powershell - 将 awk 过滤转换为等效的 Windows 命令行

powershell - PSEXEC 指定密码时不执行命令

command-prompt - 无法使用 PSExec 访问 - PSTools

powershell - 如何从SharePoint 2010工作流中调用可执行文件或Powershell脚本?

powershell - 我无法使用 Powershell StartsWith 函数