Batch File To Loop Menu

2019-09-14 15:42发布

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

1条回答
虎瘦雄心在
2楼-- · 2019-09-14 16:16

To build a menu using set /P, I recommend the following changes:

  • after all the if queries, put a goto :MENU to catch unintended entries;
  • reset the selection variable by something like set "SELECT=" before the set /P command, because set /P keep the former value of the variable in case the user presses just ENTER;
  • put quotes "" around the expressions in the if 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);
  • use the quoted syntax set [/P] "SELECT=anything" to avoid trouble with special characters;
  • in case letters are queried, add the /I switch to if to force case-insensitive comparison;
  • if you wish, you could put a 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:

@echo off

:MENU
cls
echo --- MAIN MENU ---
echo 1 - do something
echo 2 - do something else
echo Q - quit

set "SELECT="
set /P "SELECT=Type 1, 2, or Q <Enter>: "
if "%SELECT%"=="1" GOTO :SOMEWHERE
if "%SELECT%"=="2" GOTO :SOMEWHERE_ELSE
if /I "%SELECT%"=="Q" GOTO :EOF
goto :MENU

:SOMEWHERE
rem do something here...
echo.
echo Print some text.
pause
goto :MENU

:SOMEWHERE_ELSE
rem do something else here...
echo.
echo Print some other text.
pause
goto :MENU

To avoid the above mentioned troubles with the " character, modify the set /P block as follows:

set "SELECT=""
set /P "SELECT=Type 1, 2, or Q <Enter>: "
set "SELECT=%SELECT:"=%"
if "%SELECT%"=="1" GOTO :SOMEWHERE
if "%SELECT%"=="2" GOTO :SOMEWHERE_ELSE
if /I "%SELECT%"=="Q" GOTO :EOF
goto :MENU
查看更多
登录 后发表回答