≡ Menu

Choice command

In batch files, if we want to take input from the user, then choice command comes handy. Choice command provides the following features.

  • We can specify what are all the options are available for the user to choose from.
  • Timeout if user does not enter any option within the stipulated time.
  • We can specify default value if user does not enter any option.
  • Retrieve the user specified value using ERRORLEVEL environment variable.

Below are some use cases of this command.

Ask user if he/she wants to continue with the operation or not.

choice /C YN /M "Press Y to continue, N to cancel the operation."

Specify timeout period and assign a default value if the user does not enter any value within the timeout period.

choice /C YN /D Y /T 10 /M "Press Y to continue, N to cancel the operation."

Provide 3 options to the user

choice /C ABC /M "Press A for option 1, B for option 2, C for option 3"

Retrieve the user entered value.

We can get the user entered value from the environment variable ERRORLEVEL. It give thes selected option’s position in the string passed with /C option. For example if we pass ABCDEFGH with the /C option and if the user selects E, ERRORLEVEL gives the value 5. See the examples for the above listed commands.

C:\>choice /C YN /M "Press Y to continue, N to cancel the operation."
Press Y to continue, N to cancel the operation. [Y,N]?Y
C:\>echo %errorlevel%
1
C:\>choice /C ABC /M "Press A for option 1, B for option 2, C for option 3
Press A for option 1, B for option 2, C for option 3 [A,B,C]?C
C:\>echo %errorlevel%
3
C:\>
1 comment… add one
  • Daniela

    Wow! This helped me a lot, thank you sooooo so much!

Leave a Comment