【问题标题】:-command's exit code is not the same as a script's exit code- 命令的退出代码与脚本的退出代码不同
【发布时间】:2013-08-26 23:38:03
【问题描述】:

我需要使用 PowerShell -Command "& scriptname" 运行脚本,如果我从 PowerShell 返回的退出代码与脚本本身返回的退出代码相同,我会非常喜欢它。不幸的是,如果脚本返回 0,PowerShell 返回 0,如果脚本返回任何非零值,则返回 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。有什么建议吗?

【问题讨论】:

  • 我认为你想在 -command 脚本中使用 exit $lastexitcode 退出

标签: powershell exit-code


【解决方案1】:

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

如果您确实返回退出代码,它将执行您想要的操作。还将其从" 更改为',否则$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

【讨论】:

  • 感谢您的帮助!这几乎解决了我的问题。该解决方案适用于命令行,这是最初提出问题的方式,所以我会接受答案。不幸的是,我实际上是在使用 Runtime.exec 从 java 进程中启动 powershell 进程,无论我如何引用它,我的退出代码都为零。我还尝试使用反引号 (`) 转义 $lastexitcode 上的 $,但这也不起作用。
  • 谢谢。您是否尝试过像我的第二个示例中那样使用 -File 而不是 -Command?
  • 如果没有其他一些手术,使用 -File 将无法工作,因为我们使用相同的代码来启动非 powershell 进程。看起来引用被 Java 代码破坏了,Java 代码试图根据需要自动引用事物。我认为一旦我解决了它应该可以工作。再次感谢!
【解决方案2】:

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

我已经尝试过了,它似乎工作正常,但我是从 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>

【讨论】:

  • 之所以有效,是因为您在问题中使用 -File 而不是 -Command
【解决方案3】:

CAVEAT:如果您的 PowerShell 脚本返回的退出代码高于 65535,它们会翻转:

$exitCode = 65536
Exit $exitCode

如果下面的 CMD 调用上面的这个 PS1 脚本,你会得到 0

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

退出代码 65537 会给您 1 的 %errorlevel% 等。

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

Cmd /c exit 86666

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

对这一切的警告:现在这种情况时断时续地发生,没有明显的原因。

【讨论】:

    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2019-10-12
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多