Question

Having trouble getting this CHOICE script to work. Can anyone provide any insight?

@echo off

CHOICE /C:IRCQSH /T 10 /N /M "Waiting with choice..." /D H

IF ERRORLEVEL 0 ECHO "Default choice: Health"
IF ERRORLEVEL 1 ECHO "Install"
IF ERRORLEVEL 2 ECHO "Remove"
IF ERRORLEVEL 3 ECHO "Console"
IF ERRORLEVEL 4 ECHO "Quit"
IF ERRORLEVEL 5 ECHO "Start"
IF ERRORLEVEL 6 ECHO "Health"

pause
Was it helpful?

Solution

You need to change your syntax to treat ERRORLEVEL as a variable, and use the CMD equality statements, such as:

IF %ERRORLEVEL% EQU 0 ECHO "Default choice: Health"
IF %ERRORLEVEL% EQU 1 ECHO "Install"
IF %ERRORLEVEL% EQU 2 ECHO "Remove"
IF %ERRORLEVEL% EQU 3 ECHO "Console"
IF %ERRORLEVEL% EQU 4 ECHO "Quit"
IF %ERRORLEVEL% EQU 5 ECHO "Start"
IF %ERRORLEVEL% EQU 6 ECHO "Health"

The reason your code is failing is, taken from here:

IF ERRORLEVEL n statements should be read as IF Errorlevel >= number

i.e.

IF ERRORLEVEL 0 will return TRUE when the errorlevel is 64

OTHER TIPS

A couple points here:

  • The default choice does NOT return an ERRORLEVEL of zero, but the number of the choice selected. In your case, that is H, the default is equal to press H with an ERRORLEVEL of 6
  • The right way to take the value of ERRORLEVEL is enclosing it in percents and use the EQU comparison, as LittleBobbyTables said in his answer. However, there are other ways to achieve the same result.
  • The IF ERRORLEVEL Number Command test if the errorlevel value is Greater or Equal than the given number, so you may also use this form:

.

@echo off

CHOICE /C:IRCQSH /T 10 /N /M "Waiting with choice..." /D H

FOR %%E IN (6 5 4 3 2 1) DO IF ERRORLEVEL %%E GOTO LABEL-%%E

:LABEL-1 
ECHO "Install"
GOTO CONTINUE

:LABEL-2
ECHO "Remove"
GOTO CONTINUE

:LABEL-3
ECHO "Console"
GOTO CONTINUE

:LABEL-4
ECHO "Quit"
GOTO CONTINUE

:LABEL-5
ECHO "Start"
GOTO CONTINUE

:LABEL-6
ECHO "Health"

:CONTINUE
pause
  • Perhaps the simplest way to achieve the same thing is defining an array and show the appropriate element using the errorlevel value as index:

.

@echo off
setlocal EnableDelayedExpansion

rem Create an array with the desired messages (selected by numeric index)
set index=0
for %%a in ("Install" "Remove" "Console" "Quit" "Start" "Health") do (
   set /A index+=1
   set elem[!index!]=%%a
)

CHOICE /C:IRCQSH /T 10 /N /M "Waiting with choice..." /D H
echo !elem[%ERRORLEVEL%]!
pause

For a further description of Batch arrays, see: Arrays, linked lists and other data structures in cmd.exe (batch) script

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top