Make a Choice

During my sessions at Techmentor Orlando 2007 on automating with batch files, a few of my samples used the CHOICE command. I never had time to fully explain it, hence the purpose of this entry. CHOICE, when used in a batch file gives you the ability to prompt the user to make, what else, a choice. The Choice command comes from CHOICE.EXE which is part of the Windows NT/2000 Resource Kit. But I believe it is now a part of Windows 2003. If you have a Windows 2003 server you can copy CHOICE.EXE from the System32 directory to the System32 directory on your computer. Of course, you’d also have to copy it to any desktop or server.  Here’s a code snippet you could include at the beginning of your batch file to copy CHOICE.EXE from a network share if it doesn’t already exist:

set ReqFile=choice.exe
set SrcPath=\server02\public
if not exist %windir%\system32\%reqfile% COPY %srcPath%\%ReqFile%
set ReqFile=
set SrcPath=

Assuming Choice is installed, here’s how you use it.

Choice allows you to define a range of options for a user to select from and a message prompt. If you don’t specify a range of choices it defaults to YN which represents Yes or No. Let’s look at a basic example:

@echo off
Choice /M “Do you want to continue?”

if errorlevel 2 GOTO :NO
if errorlevel 1 GOTO :YES
GOTO :EOF

:NO
echo Not continuing
GOTO :EOF

:YES
echo Continuing
GOTO :EOF

:EOF

The choice command in this demo batch file simply displays a message, as represented by the /M switch. You’ll need to enclose the message prompt in quotes. When run, the script will wait until the user makes a choice. There an option to set a timeout value which I’ll show you later. The default choice is YN and it is not case-sensitive (although you can change that behaviour).  If the user does not enter one of the selected choices, the computer will beep. Assuming they enter one of the options, CHOICE will return an ErrorLevel value that corresponds to the option order.

In this example, since the default message prompt is YN, if a user selects Y, the ErrorLevel will have a value of 1 and N will have a value of 2. When you evaluate ErrorLevel, you must do it in reverse order. That is, from highest errorlevel number to lowest. In my batch file, I have code that controls script execution depending on the user’s choice.

if errorlevel 2 GOTO :NO
if errorlevel 1 GOTO :YES
GOTO :EOF

The script will jump to the appropriate script section, execute code and quit.

if errorlevel 2 GOTO :NO
if errorlevel 1 GOTO :YES
GOTO :EOF

I’ll let this sink in for a bit and be back with more on CHOICE tomorrow.

Technorati tags: , , ,