More fun with CHOICE

March 29th, 2007 by Jeffery Hicks
Last updated on March 29th, 2007

 

Let’s continue to look at CHOICE.EXE and how to use it in a batch file. Here’s what you might have for a command line menu system of common admin tasks:

@AdminMenu.bat
GOTO :MENU
:MENU

cls
echo Admin Menu
echo 1 – Create User
echo 2 – Create Group
echo 3 – Create Computer
echo 4 – Quit
Choice /C 1234 /M “Enter a menu selection”

if errorlevel 4 GOTO :EOF
if errorlevel 3 GOTO :COMPUTER
if errorlevel 2 GOTO :GROUP
if errorlevel 1 GOTO :USER
GOTO :EOF

:USER
ECHO Create New user

PAUSE
goto :MENU

:GROUP
ECHO Create New Group

PAUSE
goto :MENU

:COMPUTER

ECHO Create New computer

PAUSE
goto :MENU

:EOF

I’m echoing a menu to the screen and then using CHOICE to prompt the user to make a menu selection. The /C switch lets met specify the choice options and /M will be the message prompt. When run, the user should see something like this:

Admin Menu
1 – Create User
2 – Create Group
3 – Create Computer
4 – Quit
Enter a menu selection [1,2,3,4]?

The cursor will wait at the prompt until the user makes a selection of 1,2,3 or 4. Any other selection will cause the computer to complain with a beep. The only other way to abort is to press Ctrl-C and break out of the script so you should always give the user an option to gracefully exit your script.

As I discussed last time, the selected option will correspond to an Errorlevel value so all I have to do is jump to the right section of the script:

if errorlevel 4 GOTO :EOF
if errorlevel 3 GOTO :COMPUTER
if errorlevel 2 GOTO :GROUP
if errorlevel 1 GOTO :USER
GOTO :EOF

I probably don’t need the last GOTO :EOF statement since the user can only enter the choices I’ve made or CHOICE will beep and not move on. Still, I like including this to cover the unexpected so that the script will gracefully exit. It doesn’t cost me anything to keep it in.

Within each section, I just have placeholder code to indicate what each section will do. The Pause command waits for the user to press any key, and then script execution returns to the main menu.

:COMPUTER
ECHO Create New computer

PAUSE
goto :MENU

I’ve got one more entry on this topic so stay tuned.

Technorati tags: , , ,
 

 
[Google+]   [Facebook]   [LinkedIn]   [StumbleUpon]   [Digg]   [Reddit]   [Google Bookmark]