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.