Search code examples
windowspowershellpowershell-remoting

How can I handle remote errors with Invoke-Command


I have the following code:

Invoke-Command -ComputerName  $remoteComputerName -Credentials $cred {& c:/program.exe}

How can I return the rc from program.exe as the Invoke-Command return code, particularly when it is non-zero.?


Solution

  • as an extension for what TheMadTechnician says, you can insert what ever happend in the remote computer to a powershell object, you can even wrap it with try{} catch{} or send back only $? (same as $LASTEXITCODE) and pass it back to the script:

    $rc_oporation = Invoke-Command -ComputerName  $remoteComputerName -Credentials $cred {& c:/program.exe; $?}
    
    $rc_other_option = Invoke-Command -ComputerName  $remoteComputerName -Credentials $cred { try{& c:/program.exe} catch{"there was a problem"}  }
    

    now "$rc_oporation" will hold your answers as 0 refer to success with no errors

    hope that helps :)