Batch ERRORLEVEL not working properly

半城伤御伤魂 提交于 2019-12-12 01:43:00

问题


I've been using batch for a while now and I just recently ran into a problem I never encountered before involving ERRORLEVELS.

Here is a short program I made to show off the error.

@echo off
title Choices
CMD /C EXIT 0
echo [1] Choice 1
echo [2] Choice 2
echo [3] Choice 3
choice /c 123 /n 
IF ERRORLEVEL 1 GOTO ONE
IF ERRORLEVEL 2 GOTO TWO
IF ERRORLEVEL 3 GOTO THREE
echo Nice you broke it
pause
exit
:ONE
echo CONGRATS YOU CHOSE 1
pause
exit
:TWO
echo NICE YOU CHOSE 2
pause
exit
:THREE
echo OOH YOU CHOSE 3
pause
exit

Its very simple and all you do is press a number and it says what number you pressed. The problem is no matter what i press it always outputs what would happen when I press 1. I used to use %errorlevel% and that worked fine but then it stopped working so I switched to the new method (IF ERRORLEVEL WHATEVER) and now it wont work either.


回答1:


Please read the Microsoft support article Testing for a Specific Error Level in Batch Files.

And open a command prompt window, run if /? and read the output help, especially the paragraph about errorlevel.

The solution for your batch file is very simple, reverse the order of the lines testing on errorlevel:

@echo off
title Choices
CMD /C EXIT 0
echo [1] Choice 1
echo [2] Choice 2
echo [3] Choice 3
choice /c 123 /n 
IF ERRORLEVEL 3 GOTO THREE
IF ERRORLEVEL 2 GOTO TWO
IF ERRORLEVEL 1 GOTO ONE
echo Nice you broke it
pause
exit
:ONE
echo CONGRATS YOU CHOSE 1
pause
exit
:TWO
echo NICE YOU CHOSE 2
pause
exit
:THREE
echo OOH YOU CHOSE 3
pause
exit


来源:https://stackoverflow.com/questions/38493401/batch-errorlevel-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!