Batch file to start a service if the service is not running

Here what I want :

if servicename is running, do nothing.
if servicename is not running, then start servicename, then record the date and time.


based on my search online, here is what I have so far:


net start | find "servicename" > nul 2>&1
if not .%errorlevel%.==.0. goto startservice


:startservice
net start "servicename"
echo service restarts @ %date% %time% >> C:\checklog.txt

pause


My problem is:
It looks like that the If statement is not working. Every time I run this batch file, it runs through all the command lines.
and I got a error message said the service is already running.
Please advice.
3 answers Last reply
More about batch file start service service running
  1. Depending on the kind of service you want to play with, the "sc" command might be better than "net". Take the following service for example
    
    SERVICE_NAME: wuauserv
    DISPLAY_NAME: Windows Update
            TYPE               : 20  WIN32_SHARE_PROCESS
            STATE              : 4  RUNNING
                                    (STOPPABLE, NOT_PAUSABLE, ACCEPTS_PRESHUTDOWN)
            WIN32_EXIT_CODE    : 0  (0x0)
            SERVICE_EXIT_CODE  : 0  (0x0)
            CHECKPOINT         : 0x0
            WAIT_HINT          : 0x0
    
    If you want to know if it's running:
    sc query wuauserv | find "STATE" | find "RUNNING"
    After that command, if %errorlevel% is "0" then the service is running, if "1" it's not. You could then decide to start or stop the service:
    sc <start|stop> wuauserv
  2. I didn't see my service by using sc? but why not thing complicated?
    Anyone know what's wrong with my code or the if statement?
  3. Try:

    net start | find "servicename" > nul 2>&1
    if not .%errorlevel%.==.0. goto startservice
    goto skip


    :startservice
    net start "servicename"
    echo service restarts @ %date% %time% >> C:\checklog.txt

    :skip
    pause
Ask a new question

Read More

Programming Apps