"ERRORLEVEL 在 IF 内部"

17 浏览
0 Comments

"ERRORLEVEL 在 IF 内部"

我遇到了一个关于%ERRORLEVEL%的奇怪问题,并想知道是否有人知道原因及是否有解决方法。实际上,好像在if语句内执行的命令不会设置%ERRORLEVEL%变量。但是ERRORLEVEL(例如IF 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\' is not recognized as an internal or external command,

operable program or batch file.

OUTSIDE_IF 1

\'ThisWillSetErrorLevelTo9009ieNotRecognizedCommand\' is not recognized as an internal or external command,

operable program or batch file.

INSIDE_IF ERRORLEVEL 9009

INSIDE_IF2 ERRORLEVEL GREQ 1 9009

OUTSIDE_IF ERRORLEVEL 1

相关文章:

admin 更改状态以发布 2023年5月21日
0
0 Comments

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
)

0
0 Comments

尝试在批处理文件开头使用setlocal enabledelayedexpansion,并在IF内部使用!ERRORLEVEL!。这对我来说似乎起作用:

@echo off
setlocal enabledelayedexpansion
dir nul
echo %ERRORLEVEL%
if .1.==.1. (
  urklbkrlksdj - not a command
  echo %ERRORLEVEL%
  echo !ERRORLEVEL!
)

0