CHOICE - CMD


Overview

The CHOICE command in Windows CMD prompts the user to make a selection from a list of choices and returns the index of the selected option. It is primarily used in batch files to create menus or to accept user inputs that direct the flow of execution based on the selection made.

Syntax

The basic syntax for the CHOICE command is as follows:

CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]
  • /C choices: Specifies the set of choices to be displayed. The default choices are YN.
  • /N: Hides the list of choices in the prompt. The prompt displays only the message if used with /M.
  • /CS: Enables case-sensitivity for the choices. By default, choices are case-insensitive.
  • /T timeout: Sets a timeout in seconds for the choice to be made, after which it will automatically select the default choice.
  • /D choice: Specifies the default choice after timeout. This is used with /T.
  • /M text: Specifies the message to be displayed as the prompt.

Options/Flags

  • /C: Allows customization of available choices. For example, /C YNC could be used for Yes, No, Cancel.
  • /N: Useful for scripts where visual simplicity is desired or when choices are clearly understood from context.
  • /CS: Important in scenarios where the distinction between uppercase and lowercase inputs might signify different options.
  • /T and /D: Great for automating scripts where a default continuation is necessary after a specific period.

Examples

  1. Basic Usage:
    Prompt a user to enter Yes or No.

    CHOICE /M "Do you want to continue?"
    

    This will display the message with options [Y,N].

  2. Using Custom Choices:

    CHOICE /C WQ /M "Press W to win or Q to quit."
    

    Offers choices W and Q to the user.

  3. With Timeout:

    CHOICE /C YN /T 10 /D N /M "Continue the process? (Automatically says No after 10 seconds)"
    

    Waits for the user’s response for 10 seconds before automatically proceeding with No.

Common Issues

  • Case Sensitivity: By default, CHOICE is not case-sensitive, which can be problematic if users enter unintended inputs by capitalizing them. Use /CS to enforce case sensitivity.
  • Timeout Misunderstanding: Users might not notice the timeout is occurring if not properly mentioned in the prompt message with /M.

Integration

CHOICE can be integrated into larger scripts, combined with IF statements to branch execution based on user input:

CHOICE /C YN /M "Apply changes?"
IF ERRORLEVEL 2 GOTO NOCHANGES
IF ERRORLEVEL 1 GOTO APPLYCHANGES

:NOCHANGES
ECHO No changes were made.
EXIT

:APPLYCHANGES
ECHO Changes were applied successfully.
EXIT
  • IF: Allows branching commands based on the error level (conditionals).
  • ECHO: Displays messages or turns command echoing on or off.
  • EXIT: Quits the CMD.EXE program (command interpreter) or the current batch script.

For more details and the official documentation, you can visit Microsoft’s official page.