Search code examples
windowsbatch-filecmderrorlevel

Windows batch file - GOTO command is ignored


Here it goes stupid question but please help or my brain will explode! ;)) Some stupid thing which I don't understand...

In short: why after I choose number 7 (exit) the ERRORLEVEL returned is correct but GOTO specified label is ignored and instead it goes to allTasksReboot label...

This is my "code"...

@echo off
mode con: cols=150 lines=65
@echo ------------------------------------------------------------------------------------------------
@echo INSTALLATION MENU
@echo ------------------------------------------------------------------------------------------------
@echo [ 1 ].All tasks - Unattended with reboot on finish
@echo [ 2 ].All tasks - Unattended without reboot on finish
@echo [ 3 ].All tasks except Software group - Unattended with reboot on finish
@echo [ 4 ].All tasks except Software group - Unattended without reboot on finish
@echo [ 5 ].All tasks except Java 7 installation - Unattended without reboot on finish
@echo [ 6 ].Install only VNC - Unattended
@echo [ 7 ].Exit
@echo ------------------------------------------------------------------------------------------------
@echo ------------------------------------------------------------------------------------------------
CHOICE /C:1234567 /N /M "Choose number for installation type."
@echo You press: %ERRORLEVEL%
@pause
IF ERRORLEVEL 1 GOTO allTasksReboot
IF ERRORLEVEL 2 GOTO allTasks
IF ERRORLEVEL 3 GOTO allExceptSoftwareReboot
IF ERRORLEVEL 4 GOTO allExceptSoftware
IF ERRORLEVEL 5 GOTO allTasksExceptJava
IF ERRORLEVEL 6 GOTO onlyVnc
IF ERRORLEVEL 7 GOTO scriptend

:allTasksReboot
@echo **************************************************************************
@echo All tasks - Unattended with reboot on finish
@echo **************************************************************************
@pause
goto scriptend

:scriptend
@echo Lets exit...
@pause

:goexit

Solution

  • Remember that IF ERRORLEVEL N command test if the current ERRORLEVEL value is GREATER THAN OR EQUAL to the given number, so this command must always be executed in descending errorlevels order. You may change your IF commands this way:

    IF %ERRORLEVEL% EQU 1 GOTO allTasksReboot
    IF %ERRORLEVEL% EQU 2 GOTO allTasks
    .....
    

    Or you may simplify your code a lot if you change your labels to a rigid-format ones and use a direct GOTO command:

    CHOICE /C:1234567 /N /M "Choose number for installation type."
    @echo You press: %ERRORLEVEL%
    @pause
    GOTO LABEL-%ERRORLEVEL%
    
    :LABEL-1  allTasksReboot
    @echo **************************************************************************
    @echo All tasks - Unattended with reboot on finish
    @echo **************************************************************************
    @pause
    goto scriptend
    
    :LABEL-7  scriptend
    @echo Lets exit...
    @pause
    
    :goexit