如何捕获使用 Powershell 的 Invoke-Command 调用的 ScriptBlock 的返回值 [英] How to capture the Return Value of a ScriptBlock invoked with Powershell's Invoke-Command

查看:49
本文介绍了如何捕获使用 Powershell 的 Invoke-Command 调用的 ScriptBlock 的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与这个非常相似一个,除了我试图使用 Invoke-Command 捕获 ScriptBlock 的返回代码(所以我不能使用 -FilePath 选项).这是我的代码:

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

问题是 Invoke-Command 没有捕获 script.cmd 的返回码,所以我无法知道它是否失败.我需要知道 script.cmd 是否失败.

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.

我也尝试使用 New-PSSession(这让我可以在远程服务器上看到 script.cmd 的返回代码),但我找不到任何方法将它传递回我的调用 Powershell 脚本以实际执行任何有关失败.

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.

推荐答案

$remotesession = new-pssession -computername localhost
invoke-command -ScriptBlock { cmd /c exit 2} -Session $remotesession
$remotelastexitcode = invoke-command -ScriptBlock { $lastexitcode} -Session $remotesession
$remotelastexitcode # will return 2 in this example

  1. 使用 new-pssession 创建一个新会话
  2. 在此会话中调用您的脚本块
  3. 从这个会话中获取lastexitcode

这篇关于如何捕获使用 Powershell 的 Invoke-Command 调用的 ScriptBlock 的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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