How to capture the Return Value of a ScriptBlock invoked with Powershell's Invoke-Command

后端 未结 4 918
猫巷女王i
猫巷女王i 2020-12-13 13:16

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

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 14:08

    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.

    $result = Invoke-Command -ComputerName SERVER01 -ScriptBlock {
       ping BADHOSTNAME
       $lastexitcode
    }
    
    exit $result | Select-Object -Last 1
    

    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)

提交回复
热议问题