Jul 10, 2010

CHOICE for batch file

Last week, I found there is a command-line utility, CHOICE. It is for Batch files, *.BAT files.

The usage is simple:
CHOICE /M "Do you agree?"
This will print out a message "Do you agree? [Y,N]" and you can type in "y" key or "n" key to answer. Other keys are ignored and enter key after "y/n" is not needed.

We can also change the key choices like this:
CHOICE /C XPD /M "Do you like [X]box360 games or [P]layStation3 games? ([D]on't care)"
Now you will have "X", "P", and "D" choices instead of simply "Y/N".

The user input is then cared out with "IF ERRORLEVEL" command, eg:
CHOICE /C XPD /M "Do you like [X]box360 games or [P]layStation3 games? ([D]on't care)"
IF ERRORLEVEL 3 GOTO :DONT_CARE
IF ERRORLEVEL 2 GOTO :LIKE_PS3
IF ERRORLEVEL 1 GOTO :LIKE_XBOX
There is one more thing to note.

It is always very hard to parse user input arguments. Let's say we have a batch file, "vote.bat", that takes an argument, "xbox" or "ps3".
For example, when we want to vote for PS3, the command will be like this:
vote.bat ps3
Then in the batch file, the argument is parsed in this way:
@ECHO OFF
IF "%1" == "ps3" GOTO :VOTE_FOR_PS3
IF "%1" == "xbox" GOTO :VOTE_FOR_XBOX
Now, we need to remember that the batch file takes either "xbox" or "ps3". It shouldn't be "xbox360" or "pS3". So we now need to add HELP message like this:
@ECHO OFF
IF "%1" == "ps3" GOTO :VOTE_FOR_PS3
IF "%1" == "xbox" GOTO :VOTE_FOR_XBOX
GOTO :HELP
:HELP
ECHO USAGE: vote.bat [xbox|ps3]
With "CHOICE" command, we can make this batch file much simple:
@ECHO OFF
CHOICE /C XP /M "Vote for [X]box or [P]s3?"
There is no need to have dedicated Help sub-routine. And don't need to bother with Case-sensitiveness.

In addition to that, we can also use the batch file in this way:
ECHO x | vote.bat
This will have a same effect to a command, "vote.bat xbox", without any interactive pause.

I am thinking whenever a batch file needs to take additional input as its argument, it can be replaced with CHOICE.

Unfortunately this useful command is not available on every Windows family. It seems like CHOICE.EXE is available from Windows XP with Service pack 3.

No comments: