如果位于.bat文件中,则%errorlevel%在嵌套中的值错误 [英] wrong value of %errorlevel% in nested if in .bat file
问题描述
我已经编写了一个 .bat
文件来首先运行一个程序,如果正确完成,我将运行另一个程序并检查其返回值.
I have written a .bat
file to first run a program, if it is correctly finished I run another program and check return value of it.
first-program.exe
IF "%ERRORLEVEL%"=="0" (
second-program.exe
IF "%ERRORLEVEL%"=="0" (
ECHO OK
) ELSE (
ECHO NOK
)
)
但是第二个%ERRORLEVEL%
始终等于第一个,它没有设置为 second-program.exe
的返回值.
However the second %ERRORLEVEL%
is always equal to first, it doesn't set to the return value of second-program.exe
.
推荐答案
%ERRORLEVEL%
的两个实例都在同一代码块中,因此 both 都获得了它们的值在更新第一个实例时.考虑使用 enabledelayedexpansion
启用变量的延迟扩展,并用!ERRORLEVEL!
替换%ERRORLEVEL%
以分别更新每个实例.例如:
Both instances of %ERRORLEVEL%
are in the same block of code and thus both get their values at the moment when the first instance is updated. Consider enabling delayed expansion of variables with enabledelayedexpansion
and replacing %ERRORLEVEL%
with !ERRORLEVEL!
to update each instance individually. For instance:
@echo off
setlocal enabledelayedexpansion
first-program.exe
IF "!ERRORLEVEL!"=="0" (
second-program.exe
IF "!ERRORLEVEL!"=="0" (
ECHO OK
) ELSE (
ECHO NOK
)
)
endlocal
这篇关于如果位于.bat文件中,则%errorlevel%在嵌套中的值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!