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

こ雲淡風輕ζ 提交于 2019-11-27 22:43:38
Lars Truijens

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:\test> powershell -Command './foo.ps1; exit $LASTEXITCODE'
PS C:\test> 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:\test> powershell -File './foo.ps1'
PS C:\test> echo $lastexitcode
42
Mr. Annoyed

CAVEAT: If your PowerShell script returns exitcodes HIGHER THAN 65535, they roll over:

$exitCode = 65536
Exit $exitCode

If the following CMD calls this PS1 script above, your will get an %errorlevel% of 0

Powershell.exe "& 'MyPowershellScript.ps1' "; exit $LASTEXITCODE
SET ERR=%ERRORLEVEL%

and an exitcode of 65537 would give you an %errorlevel% of 1, etc.

Meanwhile, if a CMD calls another and the child script returns an errorlevel higher than 65535, it passes through just fine.

Cmd /c exit 86666

The CMD Will return an %errorlevel% of 86666 as expected.

CAVEAT to all of this: Now this is happening on and off for no apparent reason.

ProfessionalAmateur

How are you calling your script interactively?

I have tried this and it seems to work OK, but I call it from DOS prompt, not within PowerShell

C:\Temp>type foo.ps1
exit 42


C:\Temp>powershell -noprofile -nologo -noninteractive -executionpolicy Bypass -file .\foo.ps1

C:\Temp>echo %errorlevel%
42

c:\Temp>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!