批处理脚本输入问题

3
我有两个问题与我正在处理的批处理脚本相关。我知道批处理脚本问题很常见,但是我没有找到我的确切问题的答案,所以我想试着问一下。问题出现在菜单上的用户输入部分。
存在两个问题:1)输入的内容如果不是指定选项之一,则会导致脚本跳转到随机区域。2)一些使用外部程序的部分即使我知道语法和标志的使用通常是正确的(例如,我可以手动运行它们...),但它们仍然没有使用用户%input%(因此似乎是输入未被捕获的原因)。
第一个问题示例:
:MenuOne
echo Select one of the following options:
echo 1) x
echo 2) y
echo Q) Quit

set INPUT=
set /P INPUT=[1,2,Q]: %=%
If "%INPUT%"=="1" goto xoption
If "%INPUT%"=="2" goto yoption
If /I "%INPUT%"=="Q" goto Quit

:xoption
@REM Here goes a lot more submenus and/or options that actually run tools via cmd.

:yoption
@REM Again, menus and/or tools being invoked, in a listed menu, designed like above.

:Quit
echo Quitting...
exit

如果用户在选择提示处输入“b”,我希望脚本能够给出错误并重新显示菜单。但现在它会跳到其他菜单。我猜我需要一些ELSE语句?有没有人可以提供一个示例来完成这个操作?
第二个问题是,某些命令未正确使用%input%,导致返回一个错误,就像从未收到%input%一样。
set /P INPUT=[Testone Input]: %testone%
set /P INPUT=[Testtwo Input]: %testtwo%
commandtorun.exe -f %testone% -h %testtwo% 

感谢!
2个回答

0
在你的程序中,所有的选择都会落入下一个选择中。如果没有输入相关的选择,它将运行 :xoption:yoption。每个选择执行后,应该返回到菜单。
:MenuOne
echo Select one of the following options:
echo 1) x
echo 2) y
echo Q) Quit

set INPUT=
set /P INPUT=[1,2,Q]: %=%
If "%INPUT%"=="1" goto xoption
If "%INPUT%"=="2" goto yoption
If /I "%INPUT%"=="Q" goto Quit

echo Invalid selection.
echo.
goto MenuOne

:xoption
@REM Here goes a lot more submenus and/or options that actually run tools via cmd.
goto MenuOne

:yoption
@REM Again, menus and/or tools being invoked, in a listed menu, designed like above.
goto MenuOne

一个确保有效选择的简单方法是使用choice命令而不是set /P。这将强制用户输入一个值:
choice -c 12Q
echo %errorlevel%

choice 命令将返回所选字符的索引(在上面的示例中为 1、2 或 3)。另一个好处是它不区分大小写,因此您不必担心同时检查 Qq


谢谢!事实证明,我无法使用“choice”选项。但你建议的其他所有内容都有效。非常感激。 - Interrupt

0
最好使用choicehttp://ss64.com/nt/choice.html),因为它会持续等待直到你输入正确的内容。
CHOICE /C XYQ /M "Select of the following options [X,Y,Q]"
if errorlevel 1 goto :x
if errorlevel 2 goto :y
uf errorlevel 3 goto :q

然而,使用IF语句仍然是可能的。

set INPUT=
set /P INPUT=[1,2,Q]: %=%
If "%INPUT%"=="1" goto xoption
If "%INPUT%"=="2" goto yoption
If /I "%INPUT%"=="Q" goto Quit
rem -- will be executed only if the all the above are not true
goto :eof

针对第二个问题...您没有正确使用SET /P(变量名称应该在前面),或者您正在尝试我不理解的东西(其中使用了输入变量):
set /P testone=[Testone Input]:
set /P testtwo=[Testtwo Input]:
commandtorun.exe -f %testone% -h %testtwo% 

注意:如果操作系统是Windows XP,则默认情况下不支持“choice”命令。 - michaelb958--GoFundMonica
太棒了,我简直不敢相信我一直在错误地使用set /P。你说得对,我没有使用两个不同的变量,实际上是在覆盖旧输入。现在可以正常工作了,非常感谢!编辑:正如michaelb958所说,我尝试了一下。好吧,回到set /P,现在完全没问题了:) 谢谢 - Interrupt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接