Search code examples
batch-filecmdservicewindows-10command-prompt

Batchfile to start/stop services returns all error codes


I want to make a batchfile to quickly start/stop certain services to conserve resources when they're not needed. The file I made does the job but when run it gives me all error codes that I told it to show me if something goes wrong.

@echo off
net stop scvpn
if ERRORLEVEL 0 goto 0
if ERRORLEVEL 1 goto 1
if ERRORLEVEL 2 goto 2
if ERRORLEVEL 3 goto 3
if ERRORLEVEL 5 goto 5
if ERRORLEVEL 6 goto 6
if ERRORLEVEL 14 goto 14
if ERRORLEVEL 24 goto 24
exit
:0
echo Sophos Connect Service started.
:1
echo Function not supported.
:2
echo Access is denied, service not stopped.
:3
echo A dependent service is running.
:5
echo Control cannot be accepted.
:6
echo Sophos Connect Service is not running.
:9
echo Path not found.
:14
echo Sophos Connect Service is disabled.
:24
echo Sophos Connect Service is already paused.
pause

This is the output I get. Can anyone tell me what my error is? I'm fairly new to this way of starting/stopping services... Output of above script

It would be nice if the script only shows the one code that's relevant instead of showing all of them.


Solution

  • Two main things are wrong with your script.

    First, the syntax if errorlevel x means "if %errorlevel% is x or greater," which means that if errorlevel 0 will always be executed. The traditional ways to get around this are to either list the errorlevel values from largest to smallest or to use %errorlevel% like a regular variable.

    Second, labels are just signposts in your script that say "you are here." There is nothing to prevent the script from continuing to the next section, and since you don't have gotos or exits, every single label gets entered (because if errorlevel 0 always tells the script to go to :0).

    As a side note, you don't need gotos at all; you can just display the text based on the value of %errorlevel%, like this:

    @echo off
    net stop scvpn
    if "%errorlevel%"=="0" echo Sophos Connect Service started.
    if "%errorlevel%"=="1" echo Function not supported.
    if "%errorlevel%"=="2" echo Access is denied, service not stopped.
    if "%errorlevel%"=="3" echo A dependent service is running.
    if "%errorlevel%"=="5" echo Control cannot be accepted.
    if "%errorlevel%"=="6" echo Sophos Connect Service is not running.
    if "%errorlevel%"=="9" echo Path not found.
    if "%errorlevel%"=="14" echo Sophos Connect Service is disabled.
    if "%errorlevel%"=="24" echo Sophos Connect Service is already paused.
    pause