catching return code of a command with "invoke-command" - Powershell 2 catching return code of a command with "invoke-command" - Powershell 2 powershell powershell

catching return code of a command with "invoke-command" - Powershell 2


I think if you run a command that way on another server there is no way you can get at the return code of your script there. This is because Invoke-Command simply runs one command on the remote machine, probably within a single temporary session and you can't connect to that session again.

What you can do, however, is create a session on the remote computer and invoke your script within that session. Afterwards you can just check for the return value in that session again. So something along the lines of:

$s = New-PSSession -ComputerName <server_name>Invoke-Command -Session $s -ScriptBlock { ... }Invoke-Command -Session $s -ScriptBlock { $? }

might work. This way you get access to the same state and variables as the first Invoke-Command on the remote machine.

Also Invoke-Command is very unlikely to pass through the remote command's return value. How would you figure out then that Invoke-Command itself failed?

ETA: Ok, I misread you with regard to "return code". I was assuming you meant $?. Anyway, according to the documentation you can run a script on a remote computer as follows:

To run a local script on remote computers, use the FilePath parameter of Invoke-Command.

For example, the following command runs the Sample.ps1 script on the S1 and S2 computers:

invoke-command -computername S1, S2 -filepath C:\Test\Sample.ps1

The results of the script are returned to the local computer. You do not need to copy any files.


Here's an example...

Remote script:

try {    ... go do stuff ...} catch {    return 1    exit}return 2exit

Local script:

function RunRemote {    param ([string]$remoteIp, [string]$localScriptName)    $res = Invoke-Command -computername $remoteIp -UseSSL -Credential $mycreds -SessionOption $so -FilePath $localScriptName    return $res}$status = RunRemote $ip_name ".\Scripts\myRemoteScript.ps1"echo "Return status was $status"

$so, -UseSSL and $mycreds aren't needed if you're fully inside a trust group.This seems to work for me... good luck!


If a remote scriptblock returns an exit code, the psession will be closed. I am just checking the state of the psession. If it's closed I assume an error. Kind of hacky, but it works for my purposes.

$session = new-pssession $env:COMPUTERNAMEInvoke-Command -ScriptBlock {try { ErrorHere } Catch [system.exception] {exit 1}} -Session $sessionif ($session.State -eq "Closed"){    "Remote Script Errored out"}Remove-PSSession $session$session = new-pssession $env:COMPUTERNAMEInvoke-Command -ScriptBlock {"no exitcodes here"} -Session $sessionif ($session.State -ne "Closed"){    "Remote Script ran succesfully"}Remove-PSSession $session