选择和错误级别?

时间:2012-06-18 18:57:49

标签: batch-file

我这样做:

echo 1-exit
echo 2-about
echo 3-play
choice /c 123 >nul
if errorlevel 1 goto exit
if errorlevel 2 goto about
if errorlevel 3 goto play
:play
blah
:about
blah
:exit
cls

如果我选择“播放”选项,它会退出。我该如何防止这种情况发生?

2 个答案:

答案 0 :(得分:7)

如果choice选择返回的实际错误级别大于或等于给定值,则if errorlevel表达式的计算结果为true。因此,如果您点击3,则第一个if表达式为true并且脚本终止。请致电help if了解详情。

有两种简单的解决方法。

第一个(更好) - 将if errorlevel表达式替换为具有给定值的%ERRORLEVEL%系统变量的实际比较:

if "%ERRORLEVEL%" == "1" goto exit
if "%ERRORLEVEL%" == "2" goto about
if "%ERRORLEVEL%" == "3" goto play

第二个 - 改变比较顺序:

if errorlevel 3 goto play
if errorlevel 2 goto about
if errorlevel 1 goto exit

答案 1 :(得分:2)

解决此问题的最简单方法是使用%errorlevel%值直接转到所需的标签:

echo 1-exit
echo 2-about
echo 3-play
choice /c 123 >nul
goto option-%errorlevel%
:option-1
rem play
blah
:option-2
rem about
blah
:option-3
exit
cls
相关问题