40

で奇妙なことに遭遇し、%ERRORLEVEL%誰かがその理由を知っているかどうか、そしてそれを修正する方法があるかどうかを確認したかっただけです。%ERRORLEVEL%基本的に、ifステートメントが変数を設定しない場合にコマンドが内部で実行されるように見えます。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 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 に答える