繁体   English   中英

从 PowerShell 运行批处理文件时出现意外退出代码

[英]Unexpected exit code when running a batch file from PowerShell

我在 Microsoft Windows 环境中从Powershell调用.bat文件,并且想知道退出代码是成功还是失败。

在这种不寻常的(尽管不是很不寻常)边缘情况下似乎出现了问题。

示例 #1:

.\test1.bat

ECHO ON
setlocal enabledelayedexpansion
False
if !errorlevel! neq 0 exit /b !errorlevel!
echo "More text"

这工作正常。 False导致错误; 下一行检查状态,看到1并以代码1 exit s。 调用powershell有正确的结果。 echo $LASTEXITCODE1

示例 #2:

.\test2.bat

ECHO ON
setlocal enabledelayedexpansion
if "testing" == "testing" (
    False
    if !errorlevel! neq 0 exit /b !errorlevel!
    echo "More text"
    echo "More code"
    True
    if !errorlevel! neq 0 exit /b !errorlevel!
    echo "More code"
)

这就是困难所在。 False导致错误; 下一行检查状态,看到1并以代码1退出。 然后,调用powershell出现意外结果, echo $LASTEXITCODE is 0

只能修改批处理文件来解决问题吗?

You're seeing problematic cmd.exe behavior when batch files are called from outside cmd.exe , such as from PowerShell, their exit codes aren't reliably relayed as cmd.exe 's process exit code .

有关背景信息,请参阅此答案

解决方法

  • 按如下方式调用您的批处理文件:

     cmd /c '.\test2.bat & exit'
  • 或者,如果安装第三方模块(由我编写)是一个选项,请使用来自Native模块( Install-Module Native )的ie function ,这额外补偿了 PowerShell 向外部程序传递参数的损坏(请参阅此答案) :

     # Assuming `Install-Module Native` was run: ie.\test2.bat

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM