Question

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.?

Was it helpful?

Solution 2

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 :)

OTHER TIPS

By default Invoke-Command will pass back whatever the result of the script was. If you are not sending back any other data you can always do something like this:

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

That should return the exit code of whatever application you were trying to run.

before the above anwsers I got the following working (thanks to themadtechnician):

$s = New-PSSession -Name autobuild -ComputerName <ip address> -Credential $cred

Invoke-Command -Session $s -ScriptBlock {& 'C:\program.exe'}
$rc = Invoke-Command -Session $s -ScriptBlock {$lastexitcode}
if ($rc -ne 0)
{
    write-output "run failed ..."
    Remove-PSSession -Name autobuild
    exit 1
}
else
{
    write-output "run complete ..."
    Remove-PSSession -Name autobuild
    exit 0
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top