-command的退出代码与脚本的退出代码不同

问题描述 投票:27回答:3

我需要使用PowerShell -Command“&scriptname”运行一个脚本,如果我从PowerShell返回的退出代码与脚本本身返回的退出代码相同,我真的很喜欢它。不幸的是,如果脚本返回0,PowerShell将返回0;如果脚本返回任何非零值,则PowerShell返回1,如下所示:

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

使用[Environment] :: Exit(42)几乎可以正常工作:

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

除了脚本以交互方式运行时,它将退出整个shell。有什么建议?

powershell exit-code
3个回答
31
投票

如果你看一下你发送给-Command的部分作为一个脚本,你会发现它永远不会工作。运行foo.ps1脚本的脚本没有调用exit,因此它不会返回退出代码。

如果您确实返回退出代码,它将执行您想要的操作。同时将它从"更改为',否则$lastexitcode将在您将字符串'发送'到第二个PowerShell之前解析,如果您从PowerShell运行它。

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

PS:如果你只想运行一个脚本,还要查看-File参数。但是,如果你有像return 1那样的终止错误,也知道它不会是-Command。有关最后一个主题的更多信息,请参阅here

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

4
投票

CAVEAT:如果您的PowerShell脚本返回超过65535的exitcodes,它们会翻转:

$exitCode = 65536
Exit $exitCode

如果以下CMD调用上面的PS1脚本,则会得到%errorlevel%为0

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

并且一个65537的exitcode会给你一个%errorlevel%1,等等。

同时,如果CMD调用另一个并且子脚本返回高于65535的错误级别,则它通过就好了。

Cmd /c exit 86666

CMD将按预期返回%errorlevel%86666。

CAVEAT对所有这一切:现在这种情况正在发生,没有明显的原因。


1
投票

你是如何以交互方式调用脚本的?

我试过这个似乎工作正常,但我从DOS提示符调用它,而不是在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>
© www.soinside.com 2019 - 2024. All rights reserved.