-1

So i made a menu in batch and you have options to select what you would want to do, but if u enter a option thats not on the menu it selects the first option. how would i make it echo invalid input please try again.
menu:

echo Please select what you would like to do!
echo =========================================
echo 1)Example 1 
echo 2)Example 2
echo 3)Example 3
echo 4)Example 4
echo 5)Example 5
echo 6)Example 6
echo =========================================
set /p ans="Please enter your selection:"

if %ans%==1 (
goto a
)
if %ans%==2 (
goto b
)
if %ans%==3 (
goto c
)
if %ans%==4 (
goto f
)
if %ans%==5 (
goto g
)
if %ans%==6 (
goto h
)
ScriptKidd
  • 803
  • 1
  • 5
  • 19
Dillon
  • 1
  • 1
    @Dillon in your case, simply use `choice` – ScriptKidd Feb 21 '20 at 09:36
  • [How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?](https://stackoverflow.com/a/49834019/3074564) That answers your question and demonstrates a better method to code a choice menu using command `choice` as suggested also by Gerhard Barnard in his answer below. – Mofi Feb 21 '20 at 18:31

1 Answers1

1

Use choice. Much simpler. Here is an example

@echo off
Choice /c 123456 /m "select choice"
If not %errorlevel% equ 0 Echo you chose %errorlevel%

You can then use it to goto by creating easy manageable labels.

@echo off
Choice /c 123 /m "select choice"
Goto opt%errorlevel%
:opt3
Echo do something here for option 3
Goto :eof
:opt2
Echo do something here for option 2
Goto :eof
:opt1
Echo do something for oprion 1
:opt0
Exho You pressed ctrl+c and selected N
....

You get the idea..
Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • gud but does not avoid `Ctrl+C`, in that case `ERRORLEVEL` is set to 0 – ScriptKidd Feb 21 '20 at 09:46
  • 2
    @HackingAddict0302.. That is irrelevant. After `ctrl+c` the script is no longer executed, so `errorlevel` does not mean anything to the script. – Gerhard Feb 21 '20 at 10:15