1

I've been using batch for a while now and I just recently ran into a problem I never encountered before involving ERRORLEVELS.

Here is a short program I made to show off the error.

@echo off
title Choices
CMD /C EXIT 0
echo [1] Choice 1
echo [2] Choice 2
echo [3] Choice 3
choice /c 123 /n 
IF ERRORLEVEL 1 GOTO ONE
IF ERRORLEVEL 2 GOTO TWO
IF ERRORLEVEL 3 GOTO THREE
echo Nice you broke it
pause
exit
:ONE
echo CONGRATS YOU CHOSE 1
pause
exit
:TWO
echo NICE YOU CHOSE 2
pause
exit
:THREE
echo OOH YOU CHOSE 3
pause
exit

Its very simple and all you do is press a number and it says what number you pressed. The problem is no matter what i press it always outputs what would happen when I press 1. I used to use %errorlevel% and that worked fine but then it stopped working so I switched to the new method (IF ERRORLEVEL WHATEVER) and now it wont work either.

dan1st
  • 12,568
  • 8
  • 34
  • 67
RSher
  • 13
  • 1
  • 4
  • 4
    `If errorlevel 1` means if errorlevel is 1 **or higher**. Use in reverse order or `if errorlevel 1 if not errorlevel 2` –  Jul 21 '16 at 02:16
  • Apropos of nothing, you should use `exit /b`, not `exit`, unless you actually want to close the Command Prompt window. Newer convention is to `goto :eof`. – Aaron Mason Oct 10 '21 at 23:47

1 Answers1

2

Please read the Microsoft support article Testing for a Specific Error Level in Batch Files.

And open a command prompt window, run if /? and read the output help, especially the paragraph about errorlevel.

The solution for your batch file is very simple, reverse the order of the lines testing on errorlevel:

@echo off
title Choices
CMD /C EXIT 0
echo [1] Choice 1
echo [2] Choice 2
echo [3] Choice 3
choice /c 123 /n 
IF ERRORLEVEL 3 GOTO THREE
IF ERRORLEVEL 2 GOTO TWO
IF ERRORLEVEL 1 GOTO ONE
echo Nice you broke it
pause
exit
:ONE
echo CONGRATS YOU CHOSE 1
pause
exit
:TWO
echo NICE YOU CHOSE 2
pause
exit
:THREE
echo OOH YOU CHOSE 3
pause
exit
Mofi
  • 46,139
  • 17
  • 80
  • 143