| 116 |
| User Input in Windows 2000 Batch Files |
| In DOS and Windows 9x, the CHOICE command allowed a batch file to accept single-character |
| user input and perform different tasks based on the result. CHOICE is gone in Windows 2000 and |
| XP, but the Command Extensions (enabled by default) enhance other commands in ways that let |
| you work around the absence of CHOICE. |
| The SET command's /P switch lets you prompt for user input. For example, SET /P Choice=Type |
| the letter and press Enter will set the environment variable Choice to whatever the user enters. |
| SET also includes new syntax that lets you set an environment variable to a substring of another. |
| The expression SET foo=%bar:~1,6% sets the variable foo to a substring of the variable bar starting |
| at offset 1 (the second character) for six characters. The IF command has an /I switch for |
| case-insensitive comparisons. Used together, those features let you create a menu much as you |
| The code below shows a simple example. This batch file first gets the user's input into the variable |
| Choice. In case the user accidentally types more than one letter, it selects the substring consisting |
| of only the first letter. Then it makes a case-insensitive comparison of that letter with each of the |
| possible menu values. You can use this example as a starting point to build your own batch file |
| menu in Windows 2000 or Windows XP. |
| :: SET /P prompts for input and sets the variable |
| :: to whatever the user types |
| SET /P Choice=Type the letter and press Enter: |
| :: The syntax in the next line extracts the substring |
| :: starting at 0 (the beginning) and 1 character long |
| IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1% |
| :: /I makes the IF comparison case-insensitive |
| IF /I '%Choice%'=='A' GOTO ItemA |
| IF /I '%Choice%'=='B' GOTO ItemB |
| IF /I '%Choice%'=='C' GOTO ItemC |
| IF /I '%Choice%'=='Q' GOTO End |
| ECHO "%Choice%" is not valid. Please try again. |
| ECHO Insert commands for Item A. |
| ECHO Insert commands for Item B. |
| ECHO Insert commands for Item C. |
| This batch file implements a simple menu system. It works only at the command prompt under |
First Previous Next Last |