19

I am using "invoke-command" to execute a script on a remote machine.

invoke-command -computername <server_name> -scriptblock {command to execute the script}

My script returns "-1" when there are any errors. So, I wanted to ensure that script has executed successfully by checking the return code.

I tried as follows.

$code = invoke-command -computername ....

But it returns nothing.

Doesn't Invoke-command catch return code of script block?

Is there other way to resolve this?

Ruben Bartelink
  • 57,716
  • 25
  • 179
  • 233

6 Answers6

13

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.

Joey
  • 330,812
  • 81
  • 665
  • 668
  • odd thing in Invoke-command when running within the Jenkins context, the return code like this $returnCode = Invoke-command -file somescript.ps1 would return every from somescript.ps1. if ran within a command windows, the return value is returned properly. anyone has any idea? – koo9 Apr 17 '17 at 21:46
  • @koo9: `$returnCode` will receive _pipeline output_ of the script file. Not an exit code. – Joey Apr 18 '17 at 05:57
  • supposedly but when running the script within the Jenkins job, somehow $returncode catch all output from the ps1 script – koo9 Apr 18 '17 at 13:35
3

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:COMPUTERNAME
Invoke-Command -ScriptBlock {try { ErrorHere } Catch [system.exception] {exit 1}} -Session $session

if ($session.State -eq "Closed")
{
    "Remote Script Errored out"
}

Remove-PSSession $session

$session = new-pssession $env:COMPUTERNAME
Invoke-Command -ScriptBlock {"no exitcodes here"} -Session $session

if ($session.State -ne "Closed")
{
    "Remote Script ran succesfully"
}

Remove-PSSession $session
Cirem
  • 820
  • 1
  • 11
  • 14
3

Here's an example...

Remote script:

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

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!

Iain Ballard
  • 3,898
  • 33
  • 38
1

If you need the output from the script block and the exit code, you can throw the exit code from the block and convert if back into an integer on the calling side...

$session = new-pssession $env:COMPUTERNAME
try {
    Invoke-Command -ScriptBlock {Write-Host "This is output that should not be lost"; $exitCode = 99; throw $exitCode} -Session $session
} catch {
    $exceptionExit = echo $_.tostring()
    [int]$exceptionExit = [convert]::ToInt32($exceptionExit)
    Write-Host "`$exceptionExit = $exceptionExit"
}

This returns the standard out and the last exit code. This does require however that within your script block, any exceptions are caught and re-thrown as exit codes. Output from example ...

This is output that should not be lost
$exceptionExit = 99
Jules Clements
  • 368
  • 3
  • 8
0

I was looking to catch the error code return by a batch script called through invoke-command. Not an easy task but I found a nice and easy way to do it.

You PowerShell script is $res=invoke-command -Computername %computer% {C:\TEST\BATCH.CMD} write-host $res You'll find out the $res is the batch output, knowing this by using @echo off, >nul and echo "what you want to return" is possible!

You batch script

@echo off
echo "Start Script, do not return" > nul
echo 2

Now $res will be = 2! Then you can apply any logic in your batch.

You can even use invoke-command -AsJob Use Receive-job to get the output! In this case you don't need to use $res.

Cheers, Julien

Julien
  • 1
0

The last Powershell Invoke-Command below returns boolean True if the error code is zero from the script executed and boolean False if the return code is non-zero. Works great for detecting error codes returned from remote executions.

function executeScriptBlock($scriptString) {

    Write-Host "executeScriptBlock($scriptString) - ENTRY"

    $scriptBlock = [scriptblock]::Create($scriptString + " `n " + "return `$LASTEXITCODE")

    Invoke-Command -Session $session -ScriptBlock $scriptBlock

    $rtnCode = Invoke-Command -Session $session -ScriptBlock { $? }

    if (!$rtnCode) {
        Write-Host "executeScriptBlock - FAILED"
    }
    Else {
        Write-Host "executeScriptBlock - SUCCESSFUL"
    }
}
Freddie
  • 730
  • 1
  • 10
  • 20