40

只是偶然发现了一件奇怪的事情,%ERRORLEVEL%想看看是否有人知道为什么以及是否有办法解决它。从本质上讲,似乎在 if 语句中执行的命令没有设置%ERRORLEVEL%变量。(ERRORLEVELIF ERRORLEVEL 1,与 不同IF %ERRORLEVEL% EQU 1)检查似乎仍然可以正常工作,所以我可能可以解决它,但能够打印错误级别仍然很好。用于调试或其他什么。

@echo off
Set TESTVAR=1

tasklist | find /I "IsntRunning.exe" > NUL
echo OUTSIDE_IF %ERRORLEVEL%

ThisWillSetErrorLevelTo9009ieNotRecognizedCommand

tasklist | find /I "IsntRunning.exe" > NUL
echo OUTSIDE_IF %ERRORLEVEL%

ThisWillSetErrorLevelTo9009ieNotRecognizedCommand

IF %TESTVAR% EQU 1 (
    Set ERRORLEVEL=
    tasklist | find /I "IsntRunning.exe" > NUL
    echo INSIDE_IF  ERRORLEVEL %ERRORLEVEL%

    IF ERRORLEVEL 1 (
        echo INSIDE_IF2  ERRORLEVEL GREQ 1 %ERRORLEVEL%
    )
    IF ERRORLEVEL 2 (
        echo INSIDE_IF2  ERRORLEVEL GREQ 2 %ERRORLEVEL%
    )
    IF ERRORLEVEL 3 (
        echo INSIDE_IF2  ERRORLEVEL GREQ 3 %ERRORLEVEL%
    )
)

tasklist | find /I "IsntRunning.exe" > NUL
echo OUTSIDE_IF ERRORLEVEL %ERRORLEVEL%

@echo on

将其放入批处理文件并运行它会产生以下输出:

C:\Users\username\Documents\work>test.bat
OUTSIDE_IF 1
'ThisWillSetErrorLevelTo9009ieNotRecognizedCommand' 未被识别为内部或外部命令、可运行程序或批处理文件。
OUTSIDE_IF 1
'ThisWillSetErrorLevelTo9009ieNotRecognizedCommand' 未被识别为内部或外部命令、可运行程序或批处理文件。
INSIDE_IF ERRORLEVEL 9009
INSIDE_IF2 ERRORLEVEL GREQ 1 9009
OUTSIDE_IF ERRORLEVEL 1

相关文章:

4

2 回答 2

48

尝试在setlocal enabledelayedexpansion批处理文件的开头和. 这似乎对我有用:!ERRORLEVEL!IF

@echo off
setlocal enabledelayedexpansion
dir nul
echo %ERRORLEVEL%
if .1.==.1. (
  urklbkrlksdj - not a command
  echo %ERRORLEVEL%
  echo !ERRORLEVEL!
)
于 2010-12-06T15:45:53.060 回答
0

if errorlevel工作时不会延迟扩展,但工作方式类似于

if %errorlevel% <= Some_Value ...

@echo off

::sets errorlevel to 0
(call )
if "1" == "1" (
    rem sets errorlevel to 5
    cmd /c exit 5
    if errorlevel 4 echo this will be printed
    if errorlevel 5 echo this will be printed
    rem :::: you can use this ::::::::::::::
    if errorlevel 5 if not errorlevel 6 echo this will be printed ONLY when the errorlevel is 5
    rem :::::::::::::::::::::::::::::::::::::
    if errorlevel 6 echo this will not be printed

)
于 2020-11-11T09:46:15.460 回答