I need to check the exit code of a script block run in a remote session (started with New-PSSession) and initiated with Invoke-Command. The implementation I would prefer to use is featured here
Here is the code snippet:
$RemoteSession = New-PSSession -ComputerName ... -Credential $cred
$s = "something"
$parameters = ($parameters + $s)
$ScriptBlock = {
function PrintObjectDetails ()
{
$object = [PSCustomObject]@{
prop1 = "value1"
prop2 = "value2"
}
Write-Output $object
}
PrintObjectDetails
Write-Host $args[-1]
exit 1
}
Invoke-Command -Session $RemoteSession -ArgumentList $parameters -ScriptBlock $ScriptBlock
Invoke-Command -Session $RemoteSession -ScriptBlock { $LASTEXITCODE } -OutVariable exitCodeArray > $null
$exitCode = $exitCodeArray[0]
Note: I keep the object print function to just give context for the expected output sequence
The issue is I get 2 errors associated with the session not being open anymore for the second Invoke-Command:
Invoke-Command : Because the session state for session <id, computerName> is not equal to Open, you cannot run a command in the session. The session state is Closing.
Invoke-Command : No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands.
Why does the session close after one Invoke-Command?
How can I avoid closing it or getting $LASTEXITCODE from that run (without disrupting the output sequence)?