使用“invoke-command"捕获命令的返回码;- Powershell 2 [英] catching return code of a command with "invoke-command" - Powershell 2

查看:97
本文介绍了使用“invoke-command"捕获命令的返回码;- Powershell 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用调用命令"在远程机器上执行脚本.

I am using "invoke-command" to execute a script on a remote machine.

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

当出现任何错误时,我的脚本返回-1".所以,我想通过检查返回码来确保脚本已成功执行.

My script returns "-1" when there are any errors. So, I wanted to ensure that script has executed successfully by checking the return code.

我尝试如下.

$code = invoke-command -computername ....

但它什么都不返回.

Invoke-command 不捕获脚本块的返回码吗?

Doesn't Invoke-command catch return code of script block?

有没有其他方法可以解决这个问题?

Is there other way to resolve this?

推荐答案

我认为如果您在另一台服务器上以这种方式运行命令,您将无法在那里获得脚本的返回码.这是因为 Invoke-Command 只是在远程机器上运行一个命令,可能是在一个临时会话中,您无法再次连接到该会话.

I think if you run a command that way on another server there is no way you can get at the return code of your script there. This is because Invoke-Command simply runs one command on the remote machine, probably within a single temporary session and you can't connect to that session again.

可以做的是在远程计算机上创建一个会话并在该会话中调用您的脚本.之后,您可以再次检查该会话中的返回值.所以类似的东西:

What you can do, however, is create a session on the remote computer and invoke your script within that session. Afterwards you can just check for the return value in that session again. So something along the lines of:

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

可能有用.通过这种方式,您可以访问与远程计算机上的第一个 Invoke-Command 相同的状态和变量.

might work. This way you get access to the same state and variables as the first Invoke-Command on the remote machine.

还有 Invoke-Command 不太可能通过远程命令的返回值.那么你如何确定 Invoke-Command 本身失败了?

Also Invoke-Command is very unlikely to pass through the remote command's return value. How would you figure out then that Invoke-Command itself failed?

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

ETA: Ok, I misread you with regard to "return code". I was assuming you meant $?. Anyway, according to the documentation you can run a script on a remote computer as follows:

要在远程计算机上运行本地脚本,请使用FilePath Invoke-Command 的参数.

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

例如,以下命令运行 Sample.ps1 脚本在 S1S2 计算机上:

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.

这篇关于使用“invoke-command"捕获命令的返回码;- Powershell 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆