如何捕获使用 Powershell 的 Invoke-Command 调用的 ScriptBlock 的返回值
我的问题与这个非常相似,除了我尝试使用 Invoke-Command 捕获 ScriptBlock 的返回代码(因此我无法使用 -FilePath 选项)。这是我的代码:
Invoke-Command -computername $server {\\fileserver\script.cmd $args} -ArgumentList $args
exit $LASTEXITCODE
问题是 Invoke-Command 无法捕获 script.cmd 的返回代码,因此我无法知道它是否失败。我需要知道 script.cmd 是否失败。
我也尝试使用 New-PSSession (这让我可以在远程服务器上查看 script.cmd 的返回代码),但我找不到任何方法将其传递回我的调用 Powershell 脚本以实际对失败执行任何操作。
My question is very similar to this one, except I'm trying to capture the return code of a ScriptBlock using Invoke-Command (so I can't use the -FilePath option). Here's my code:
Invoke-Command -computername $server {\\fileserver\script.cmd $args} -ArgumentList $args
exit $LASTEXITCODE
The problem is that Invoke-Command doesn't capture the return code of script.cmd, so I have no way of knowing if it failed or not. I need to be able to know if script.cmd failed.
I tried using a New-PSSession as well (which lets me see script.cmd's return code on the remote server) but I can't find any way to pass it back to my calling Powershell script to actually DO anything about the failure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
主机:HOST1
输出:Ping 请求找不到主机 badhostname。请检查名称并重试
退出代码:1
主机:HOST2
输出:Ping 请求找不到主机 badhostname。请检查名称并重试。
退出代码:1
Host : HOST1
Output : Ping request could not find host badhostname. Please check the name and try again
ExitCode : 1
Host : HOST2
Output : Ping request could not find host badhostname. Please check the name and try again.
ExitCode : 1
我最近一直在使用另一种方法来解决这个问题。来自远程计算机上运行的脚本的各种输出是一个数组。
$result
变量将包含 ping 输出消息和$lastexitcode
的数组。如果远程脚本的退出代码最后输出,则可以从完整结果中获取它而无需解析。要获取退出代码之前的其余输出,只需:
$结果|选择对象-First $(result.Count-1)
I have been using another method lately to solve this problem. The various outputs that come from the script running on the remote computer are an array.
The
$result
variable will contain an array of the ping output message and the$lastexitcode
. If the exit code from the remote script is output last then it can be fetched from the complete result without parsing.To get the rest of the output before the exit code it's just:
$result | Select-Object -First $(result.Count-1)
@jon Z 的答案很好,但这更简单:
当然,如果您的命令产生输出,您必须抑制它或解析它以获取退出代码,在这种情况下 @jon Z 的答案可能会更好。
@jon Z's answer is good, but this is simpler:
Of course if your command produces output you'll have to suppress it or parse it to get the exit code, in which case @jon Z's answer may be better.
最好使用
return
而不是exit
。例如:
It is better to use
return
instead ofexit
.For example: