In this article, we will discuss how to use the choice command in a batch script to get user input and return an ERRORLEVEL variable.
Understanding the choice Command
The choice command is a built-in command in Windows batch scripts that allows users to select an option from a list. It displays a numbered list of options and waits for the user to press the Enter key with the corresponding number. The choice command sets the ERRORLEVEL variable based on the user's selection.
Syntax
The syntax for the choice command is as follows:
choice [/C [string]] [/N] [/T timeout] [/D default] [/M "message"] [/V]
/C: Specifies the choices the user can select. It is a required parameter and can contain one or more options, separated by commas./N: Disables numbering of the choices./T: Sets the timeout for thechoicecommand in milliseconds. If not specified, the default is 30000 milliseconds (30 seconds)./D: Specifies the default choice. If not specified, there is no default choice./M: Displays a message before showing the choices./V: Displays the choices vertically instead of horizontally.
Example
Let's create a simple batch script that uses the choice command to get user input and return the ERRORLEVEL variable.
@echo off
echo Select an option:
echo.
echo 1. Option A
echo 2. Option B
echo.
choice /C 12 /N /T 10000
if %ERRORLEVEL% equ 1 (
echo You selected Option A.
) else if %ERRORLEVEL% equ 2 (
echo You selected Option B.
) else (
echo Invalid selection.
)
In this example, the user is presented with two options: Option A and Option B. The choice command waits for 10000 milliseconds (10 seconds) for user input. If the user presses 1, the ERRORLEVEL variable is set to 1, and the script executes the code inside the first if block. Similarly, if the user presses 2, the ERRORLEVEL variable is set to 2, and the script executes the code inside the second if block. If the user presses any other key, the ERRORLEVEL variable remains unchanged, and the script executes the code inside the last if block.
References
Summary
- The
choicecommand in Windows batch scripts allows users to select an option from a list and sets theERRORLEVELvariable based on the user's selection. - The syntax for the
choicecommand includes options for customizing the choices, timeout, message, and default choice. - To use the
choicecommand, create a batch script, write the script logic, and use thechoicecommand with the appropriate parameters. The script should check theERRORLEVELvariable to determine the user's selection.