Snoopy135
Snoopy135

Reputation: 21

batch choice command not working

Okay I am trying to ask the user the below question in a batch file but don't think that I am entering the correct choice command.

    echo Would you like to know the time? (Y/N)
    CHOICE /C YN /N
    GOTO OPTION-%ERRORLEVEL%

    :OPTION-Y  Yes 
    echo %time%
    goto cont

    :OPTION-N  No

    :cont

P.S today is my first day of the couse so I am a newbie, please don't judge.

Upvotes: 2

Views: 2275

Answers (3)

user7818749
user7818749

Reputation:

Because %errorlevel% is a number not Y or N

Your labels should be :OPTION-1 and :OPTION-2:

@echo off
echo Would you like to know the time? (Y/N)
CHOICE /C YN /N
GOTO OPTION-%ERRORLEVEL%

:OPTION-1
echo %time%
goto cont

:OPTION-2

:cont

Here is another example so you can understand how it assigns the %errorlevel% number to the key you selected.

@echo off
:start
cls
CHOICE /C YNM /N /M "Should I display the Time? Select (Yes (Y)  No (N) or Maybe (M))"
if %errorlevel%==1 echo %time%
if %errorlevel%==2 echo Ok, I won't then
if %errorlevel%==3 echo it is fine, I will ask again in 10 seconds & timeout /T 10 & goto :start

Here you can see it assigns the first key to %errorlevel% 1, the second key to %errorlevel% 2 and third key to %errorlevel% 3 etc.

Upvotes: 2

Compo
Compo

Reputation: 38604

You could also reduce all of your provided snippet to two lines, (continuing your script beneath them as necessary):

Choice /M "Would you like to know the time"
If Not ErrorLevel 2 Echo %TIME% & Timeout 3 >Nul

Upvotes: 0

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10764

CHOICE does not return the selected key as %ERRORLEVEL%, it returns the index of the selected key - that is, for CHOICE /C YN, if you select Y, %ERRORLEVEL% will be 1; for N, it will be 2. See SS64 on CHOICE.

You also have to be careful about the order that you test %ERRORLEVEL%; the standard construct IF ERRORLEVEL n ... is actually testing to see whether %ERRORLEVEL% is equal to or greater than n. See SS64 on ERRORLEVEL.

Upvotes: 0

Related Questions