如何防止用户 select 除批处理中定义的默认值外的任何选项

How to prevent user select any option except defaults defined in the batch

除了相关菜单中定义的默认选项外,我想阻止用户选择。

ECHO Select a file
ECHO.
ECHO 1. Process File and commands
ECHO 2. Another File and commands
ECHO 3. Yet another file and its commands
ECHO 4. Disconnect
ECHO 5. Exit
ECHO.
set /p choice="Choose an option: "
if "%choice%"=="1" goto smenu_1 
if "%choice%"=="2" goto smenu_2
if "%choice%"=="3" goto smenu_3
if "%choice%"=="4" goto smenu_4
if "%choice%"=="5" goto End



:smenu_1
ECHO Select another option
ECHO.
ECHO 1 - This is an option
ECHO 2 - Back to Start
ECHO.
SET /P M=Choose an option:
IF %M%==1 GOTO This_Submenu_Does_Multiple_Commands
IF %M%==2 GOTO start

这是我的示例代码。在主菜单中,如果我输入“6”,它会自动转到第一个子菜单。我尝试了这里在类似问题中或通过网络提供的许多选项,如输入验证或类似内容。我想让用户输入选项中给出的数字之一。例如,在主菜单中,如果选择了“6”或者“25”,它应该警告用户选择了错误的选项并尝试更多。我希望所有子菜单都有这个。另外,此时又出现了一个问题:菜单选项可能会超过30个选项,这意味着可能不会只有个位数。你能告诉我如何限制用户输入尽可能多的菜单选项吗(包括子菜单选项可能会因他们自己的选项数量而异)。提前致谢。

添加 :menu 作为批处理的第一行,并在 if "%choice%"=="5" goto End 行的正下方添加 cls & goto menu

如果您仍想使用连续的数字,并希望有超过九个可能的条目的可能性,您可以使用与我在 中使用的完全相同的方法来完成。它仍然使用 Set /P,但使用 Set 命令和 FindStr 来执行输入验证。

示例:

@Echo Off
SetLocal EnableExtensions

:Menu
ClS
Echo Menu of options
Echo(
Echo  1. Process file and commands
Echo  2. Another file and commands
Echo  3. Yet another file and commands
Echo  4. And another file and commands
Echo  5. A different file and commands
Echo  6. Some other file and commands
Echo  7. Alternative file and commands
Echo  8. Perhaps this file and commands
Echo  9. Or even this file and its commands
Echo 10. Disconnect
Echo 11. Exit
Echo(

For /F "Delims==" %%G In ('"(Set option) 2>NUL"') Do Set "%%G="
Set /P option="Please type your chosen option number, and press ENTER>"
Set option | %SystemRoot%\System32\findstr.exe /R "^option=[123456789]$ ^option=1[01]$" 1>NUL || GoTo Menu

:Validated
ClS
Echo(
Echo Your chosen option was %option%
%SystemRoot%\System32\timeout.exe /T 5

当您的选项数量发生变化时,您只需根据需要更改 findstr.exe 的匹配字符串。例如,对于二十七个选项 (1..27),"^option=[123456789]$ ^option=1[0123456789]$ ^option=2[01234567]$"。要了解如何使用 FindStr,请打开命令提示符 window,键入 findstr /? 并按 ENTER 键。