gpt4 book ai didi

powershell - 使用 “invoke-command”捕获命令的返回码-Powershell 2

转载 作者:行者123 更新时间:2023-12-03 13:33:59 24 4
gpt4 key购买 nike

我正在使用“调用命令”在远程计算机上执行脚本。

invoke-command -computername <server_name> -scriptblock {command to execute the script}

出现任何错误时,我的脚本将返回“-1”。
因此,我想通过检查返回代码来确保脚本已成功执行。

我尝试如下。
$code = invoke-command -computername ....

但是它什么也没返回。
Invoke-command不捕获脚本块的返回码吗?

还有其他解决方法吗?

最佳答案

我认为,如果您在另一台服务器上以这种方式运行命令,则无法在该处获得脚本的返回代码。这是因为Invoke-Command可能只是在一个临时 session 中在远程计算机上运行一个命令,而您无法再次连接到该 session 。

但是,您可以做的是在远程计算机上创建一个 session ,然后在该 session 中调用脚本。之后,您可以再次检查该 session 中的返回值。因此,遵循以下原则:

$s = New-PSSession -ComputerName <server_name>
Invoke-Command -Session $s -ScriptBlock { ... }
Invoke-Command -Session $s -ScriptBlock { $? }

可能有用。这样,您就可以访问与远程计算机上的第一个 Invoke-Command相同的状态和变量。

另外, Invoke-Command不太可能通过远程命令的返回值传递。您如何确定 Invoke-Command本身失败了?

预计到达时间:好,关于“返回码”,我误读了您。我假设你的意思是 $?。无论如何,根据文档,您可以在远程计算机上运行脚本,如下所示:

To run a local script on remote computers, use the FilePath parameter of Invoke-Command.

For example, the following command runs the Sample.ps1 script on the S1 and S2 computers:

invoke-command -computername S1, S2 -filepath C:\Test\Sample.ps1

The results of the script are returned to the local computer. You do not need to copy any files.

关于powershell - 使用 “invoke-command”捕获命令的返回码-Powershell 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1210942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com