从 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,并使用代码1exits。 调用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 $LASTEXITCODE0

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

当从cmd.exe外部(例如从 PowerShell)调用批处理文件,您会看到有问题的cmd.exe行为,它们的退出代码不能可靠地中继为cmd.exe的进程退出代码

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

解决方法

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

    cmd /c '.test2.bat & exit'
    
  • 或者,如果可以选择安装第三方模块(由我创作),请使用Native模块(Install-Module Native)中的ie函数,该函数还可以补偿PowerShell对外部程序的参数传递(请参阅此答案):

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

最新更新