Skip to main content

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
# https://stackoverflow.com/questions/8549184/how-to-capture-the-return-value-of-a-scriptblock-invoked-with-powershells-invok

$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 @{ComputerName=$Env:COMPUTERNAME; Output=$output; ExitCode=$exitCode}
}

# To capture the results from the remote computers:
$results = Invoke-Command -ComputerName host1, host2 -ScriptBlock $script
# or without the -ComputerName param:
$results = Invoke-Command -ScriptBlock $script

$results | select ComputerName, Output, ExitCode | Format-List

# ComputerName :
# Output       : ping: cannot resolve badhostname: Unknown host
# ExitCode     : 68