我正在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 $LASTEXITCODE
是1
.
示例 #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
0
。
只能修改批处理文件来解决问题吗?
当从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