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

Status
Not open for further replies.

beidog

Distinguished
Oct 19, 2010
8
0
18,510
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.
 

Zenthar

Distinguished
Dec 31, 2007
250
0
18,960
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
Code:
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:
Code:
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:
Code:
sc <start|stop> wuauserv
 
Status
Not open for further replies.