In Windows batch, I'm asking the user whether he wants to use the program's internal default or wants to set his own parameters, but no matter what the user sets as an answer, the program always jumps straight to the main routine using the internal defaults. This is my code:
@echo off
setlocal EnableDelayedExpansion
choice /C:yn /M "Use internal defaults? "
if errorlevel==1 goto yes
if errorlevel==2 goto no
rem use default
:yes
set "MYNUMBER=5"
goto run
rem let user define another number
:no
set /P MYNUMBER="Please set a number: "
goto run
rem main routine
:run
echo %MYNUMBER%
pause
What am I missing?
And since we're at it: how can I force the program to wait for the user to hit "Enter" after typing his choice? Right now, it starts directly after typing "y" or "n".
if errorlevel==1implies if errorlevel equal 1 or greater. A different thing is using the environment variable%errorlevel%as long the var isn't altered (by another error) you can check for a distinct value. SeeHelp ifor view onlneif errorlevel==1is completely wrong syntax. The correct syntax can be read by opening a cmd window and run the commandif /?which outputs the help of command IF explaining on first help page the correct syntaxif [not] errorlevel number command. There is no string comparison operator==. And this condition is true if exit code of previous command or application is greater or equal the number. So use firstif errorlevel 2 goto noand no moreifis needed because next command lines to execute on exit code being not greater or equal 2 are the lines for user choicey.set /Pinstead ofchoice; but then also account for invalid user input...errorlevelwas not obvious to me. Now, usingset /P USER_CHOICE="Use defaults? (Y/N)"and then checking it usingifdoes the job.