- 1 year ago
Batch choice command runs both choices instead of just the one I selected
The behavior you described, where both choices in a choice
command are executed instead of just the selected one, typically occurs when you forget to include the GOTO
command after each choice option. The GOTO
command is used to direct the flow of the script to the desired label based on the selected choice.
Here's an example of how to correctly structure a batch script with the choice
command:
batch@echo off
echo Select an option:
echo 1. Option 1
echo 2. Option 2
choice /C 12
REM Process the selected option
IF %ERRORLEVEL% EQU 1 (
echo Option 1 selected
GOTO Option1Label
)
IF %ERRORLEVEL% EQU 2 (
echo Option 2 selected
GOTO Option2Label
)
REM Label for Option 1
:Option1Label
echo Executing Option 1
REM Add your code here for Option 1
GOTO End
REM Label for Option 2
:Option2Label
echo Executing Option 2
REM Add your code here for Option 2
GOTO End
REM End of the script
:End
echo Script execution complete.
In the example above, after each IF %ERRORLEVEL% EQU <value>
condition, the script uses the GOTO
command to jump to the appropriate label based on the selected choice. This ensures that only the code block associated with the selected choice is executed.
Remember to replace the placeholder code and labels (Option1Label
, Option2Label
, and End
) with your actual code and labels.
By including the GOTO
command after each choice option, you can control the flow of the script and ensure that only the selected choice is executed.