Get the return code of remote job.

Hi, I am invoking Remote Script with Invoke_Command. If RemoteScript returns the error code say 2, how can I get this error code on host machine? Below is code snippet.

$job = Invoke-Command -ComputerName $SlaveMachine -ScriptBlock {
param([string] $RemoteScript,
[string] $controller
)
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
& powershell.exe -File $RemoteScript -initiator $controller
} -ArgumentList $Script, $thisMachine -Credential $C -AsJob

 

Remote Script:

$Testreturncode = 2

return $Testreturncode

You’re invoking it with -AsJob, which executes as a background task.

Use Get-Job to retrieve references to background tasks, Wait-Job to stall until completion, and then Receive-Job to retrieve any data that background tasks are holding for you on completion:

$Jobs = Get-Job
$Jobs | Wait-Job
$Jobs | Receive-Job

Thanks Joel.

I do get the Job results with receive-job but I am looking specifically for the value of $Testreturncode. I want to capture this return code in a variable and do specific handling based on return code.

 

That depends on what else your function / job does and if it outputs anything prior to the return code as well. On the assumption that the return code is the very last thing that the job outputs, you can reliably do something along these lines:

$Job | Wait-Job
$JobOutput = $Job | Receive-Job
$ReturnCode = @($JobOutput)[-1]

Thanks Joel. This works but it seems unreliable. If someone adds even a Write-Output line in scriptBlock after the script, It will not return the expected value in return code.

$job = Invoke-Command -ComputerName $SlaveMachine -ScriptBlock {
param([string] $RemoteScript,
[string] $controller
)
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
& powershell.exe -File $RemoteScript -initiator $controller

Write-Output "Test result"
} -ArgumentList $Script, $thisMachine -Credential $C -AsJob

 

    Wait-Job $job | Out-Null
    $r = Receive-Job $job
    $var = @($r)[-1]

Remote Script:

$Testreturncode = 2

return $Testreturncode

I do not get the expected output in $var in above case. I tried using $LASTEXITCODE but I dont get the correct value of it outside the scriptblock.

 

 

Return code is not the same as $LASTEXITCODE. The latter is only populated when running a compiled application directly – and you’re running it via a native remoting command.

And yes, additional output may butcher things a bit. Return in powershell is not “return just this data”; it’s more analogous to “return this AND all previous output”.

The code I posted ought to work fine, but I think the issue is that you’re calling the powershell.exe instead of just invoking the script in the existing session

If instead you simply invoke the script as-is it should work more easily:

#replace: & powershell.exe -File $RemoteScript -initiator $controller
& $RemoteScript -Initiator $Controller