Search code examples
windowsbatch-filecmdcommand

Batch File Choice Command Loops


I've written a simple batch file with only a Choice command. The code is as follows:

Choice /C yn /M /t 5 "Do you want to continue"
If Errorlevel 2 Goto No


If Errorlevel 1 Goto Yes

Goto End
:No
Echo You selected No


Goto End
:Yes
Echo You selected Yes


:End

Problem is when I run it it doesn't wait for input .. It loops through and doesn't stop. I don't know what to do or why it doesn't work. I created a batch file at work with a choice command more complex than this and it works fine. But that file wouldn't work on my computer either.

Also if i type the choice command straight in cmd it works fine but batch file loops

Any suggestions? thanks

here is a link to a video that shows exactly what its doing http://youtu.be/4TkwlR7yMb8


Solution

  • The /M switch is for Message, you need to write the text after /M. You also need to include the /D switch (for Default), because you specified how long they have to make a selection with /T. The default option is the option that will be selected automatically if the user doesn't make a selection in, for your example, five seconds. The below example will automatically choose n at the end of time.

    Choice /C yn /D n /T 5 /M "Do you want to continue"
    

    The name of your batch file must not be the same as a command used inside your batch file. When you make a call to an executable (i.e. choice), cmd will look in the current directory for a file of that name before looking at directories in the path variable. So, because your batch file is called choice.bat, when you run the command choice /c ... you are actually making a call to the batch file itself, and not the choice command. Re-name your batch file.