Search code examples
cmderrorlevel

CMD Script Errorlevel Misbehavior with IF statement


Expected outcome of the following script: PERMPING if user presses P, or PINGLOOP if user presses T. However, no matter what the user presses, the script echos both. Any idea what gives?

CHOICE /C:PT /N /M "Ping permanently (P) or temporarily (T) (%pingTimes% times)?"
echo %ERRORLEVEL%
IF ERRORLEVEL 1 ECHO PERMPING
IF ERRORLEVEL 2 ECHO PINGLOOP

Solution

  • I suspect you are not acurately reporting the results of your code. The code you have posted should print both if P is pressed, and only print PINGLOOP if T is pressed. The behavior is due to how the IF ERRORLEVEL statement works, as is explained by the help. To get help on any command, simply type HELP commandName or commandName /? from a command prompt. In your case, you could use IF /? to see the following

    Performs conditional processing in batch programs.
    
    IF [NOT] ERRORLEVEL number command
    ...
      ERRORLEVEL number Specifies a true condition if the last program run
                        returned an exit code equal to or greater than the number
                        specified.
    ...
    

    You have 2 choices to make your code work:

    Test the conditions in decreasing numerical order and use the ELSE clause

    CHOICE /C:PT /N /M "Ping permanently (P) or temporarily (T) (%pingTimes% times)?"
    echo %ERRORLEVEL%
    IF ERRORLEVEL 2 (
      ECHO PINGLOOP
    ) ELSE IF ERRORLEVEL 1 (
      ECHO PERMPING
    )
    

    or use IF %ERRORLEVEL%==N

    CHOICE /C:PT /N /M "Ping permanently (P) or temporarily (T) (%pingTimes% times)?"
    echo %ERRORLEVEL%
    IF %ERRORLEVEL% == 1 ECHO PERMPING
    IF %ERRORLEVEL% == 2 ECHO PINGLOOP