views:

1683

answers:

2

Hi, 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?

Any help will be highly appreciated.

Thanks in advance Buddhika

A: 

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

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