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
1.2k views
in Technique[技术] by (71.8m points)

powershell - -command's exit code is not the same as a script's exit code

I need to run a script with PowerShell -Command "& scriptname", and I would really like it if the exit code I got back from PowerShell was the same as the exit code the script itself returned. Unfortunately, PowerShell returns 0 if the script returns 0, and 1 if the script returns any non-zero value as illustrated below:

PS C:est> cat foo.ps1
exit 42
PS C:est> ./foo.ps1
PS C:est> echo $lastexitcode
42
PS C:est> powershell -Command "exit 42"
PS C:est> echo $lastexitcode
42
PS C:est> powershell -Command "& ./foo.ps1"
PS C:est> echo $lastexitcode
1
PS C:est>

Using [Environment]::Exit(42) almost works:

PS C:est> cat .az.ps1
[Environment]::Exit(42)
PS C:est> powershell -Command "& ./baz.ps1"
PS C:est> echo $lastexitcode
42
PS C:est>

Except that when the script is run interactively, it exits the whole shell. Any suggestions?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you look at the part you are sending to -Command as a script you will see it would never work. The script running the foo.ps1 script does not have a call to exit, so it does not return an exit code.

If you do return an exit code it will do what you want. Also change it from " to ', otherwise $lastexitcode will be resolved before you 'send' the string to the second PowerShell, if you run it from PowerShell.

PS C:est> powershell -Command './foo.ps1; exit $LASTEXITCODE'
PS C:est> echo $lastexitcode
42

PS: Also check out the -File parameter if you just want to run a script. But also know it does not return 1 if you have a terminating error as -Command does. See here for more on that last topic.

PS C:est> powershell -File './foo.ps1'
PS C:est> echo $lastexitcode
42

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...