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

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


$remotesession = new-pssession -computername localhostinvoke-command -ScriptBlock { cmd /c exit 2} -Session $remotesession$remotelastexitcode = invoke-command -ScriptBlock { $lastexitcode} -Session $remotesession$remotelastexitcode # will return 2 in this example
  1. Create a new session using new-pssession
  2. Invoke your scripblock in this session
  3. Fetch the lastexitcode from this session


$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

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


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)