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

$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. Create a new session using new-pssession
  2. Invoke your scripblock in this session
  3. Fetch the lastexitcode from this session

Leave a Comment