【问题标题】:ERRORLEVEL inside IFIF 内的 ERRORLEVEL
【发布时间】:2011-05-21 01:20:51
【问题描述】:

刚刚偶然发现%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' 未被识别为内部或外部命令, 可运行的程序或批处理文件。
OUTSIDE_IF 1
'ThisWillSetErrorLevelTo9009ieNotRecognizedCommand' 未被识别为内部或外部命令, 可运行的程序或批处理文件。
INSIDE_IF 错误级别 9009
INSIDE_IF2 错误级别 GREQ 1 9009
OUTSIDE_IF 错误级别 1

相关文章:

【问题讨论】:

    标签: batch-file errorlevel


    【解决方案1】:

    尝试在批处理文件的开头使用setlocal enabledelayedexpansion,并在IF 中使用!ERRORLEVEL!。这似乎对我有用:

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

    【讨论】:

    【解决方案2】:

    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
    
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多