I'm creating a batch file that will launch when I login to my user account. I followed this tutorial to create a batch file with a menu. It works, however, if the user enters a number that is not listed, I want it to go back to the menu. How would I implement that?
Side note: I understand I could use something more flexible like Powershell, however, I prefer batch files.
Here is what I have so far:
@ECHO OFF
CLS
:MENU
echo Welcome %USERNAME%
echo 1 - Start KeePass
echo 2 - Backup
echo 3 - Exit
SET /P M=Type 1,2,3 then press Enter:
IF %M%==1 GOTO StarKeePass
IF %M%==2 GOTO Backup
IF %M%==3 GOTO :EOF
:StarKeePass
SET keePass="%USERPROFILE%\KeePass\KeePass-2.30\KeePass.exe"
SET kdb="%USERPROFILE%\KeePass\PasswordDatabase\PasswordDatabase.kdbx"
echo I'll start KeePass for You
START "" %keePass% %kdb%
GOTO MENU
:Backup
SET backup="%USERPROFILE%\backup.bat"
call %backup%
GOTO MENU
To build a menu using
set /P
, I recommend the following changes:if
queries, put agoto :MENU
to catch unintended entries;set "SELECT="
before theset /P
command, becauseset /P
keep the former value of the variable in case the user presses just ENTER;""
around the expressions in theif
statements to avoid syntax errors in case the variable is empty or it contains some characters that have special meanings (^
&
(
)
<
>
|
; the"
character still causes problems though);set [/P] "SELECT=anything"
to avoid trouble with special characters;/I
switch toif
to force case-insensitive comparison;cls
command after the:MENU
label to let the screen be built up every time you return to the menu;Here is an example that demonstrates what I am talking about:
To avoid the above mentioned troubles with the
"
character, modify theset /P
block as follows: