如何捕获使用Powershell的Invoke-Command调用的ScriptBlock的返回值

Jay*_*ang 29 powershell return-value exit-code windows-scripting invoke-command

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

Invoke-Command -computername $server {\\fileserver\script.cmd $args} -ArgumentList $args
exit $LASTEXITCODE
Run Code Online (Sandbox Code Playgroud)

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

我也尝试使用New-PSSession(这让我看到了远程服务器上的script.cmd的返回代码)但是我找不到任何方法将它传递回我的调用Powershell脚本来实际处理有关失败的任何事情.

jon*_*n Z 40

$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
Run Code Online (Sandbox Code Playgroud)
  1. 使用new-pssession创建一个新会话
  2. 在此会话中调用您的scripblock
  3. 从此会话中获取lastexitcode

  • 不会`$ remotelastexitcode = invoke-command -ScriptBlock {cmd/c exit 2; $ lastexitcode} -Session $ remotesession`工作?由于您使用会话来提供多个命令,因此您可以阻止它. (6认同)
  • @manojlds是的,捕获第一个scriptblock中的lastexitcode也可以. (2认同)

Mat*_*and 6

$script = {
    # Call exe and combine all output streams so nothing is missed
    $output = ping badhostname *>&1

    # Save lastexitcode right after call to exe completes
    $exitCode = $LASTEXITCODE

    # Return the output and the exitcode using a hashtable
    New-Object -TypeName PSCustomObject -Property @{Host=$env:computername; Output=$output; ExitCode=$exitCode}
}

# Capture the results from the remote computers
$results = Invoke-Command -ComputerName host1, host2 -ScriptBlock $script

$results | select Host, Output, ExitCode | Format-List
Run Code Online (Sandbox Code Playgroud)

主机:HOST1
输出:Ping请求找不到主机badhostname.请检查名称,然后重试
ExitCode:1

主机:HOST2
输出:Ping请求找不到主机badhostname.请检查名称,然后重试.
ExitCode:1