Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

catching return code of a command with "invoke-command" - Powershell 2

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:TestSample.ps1

The results of the script are returned to the local computer. You do not need to copy any files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...