Sign in with
Sign up | Sign in
Your question

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

Last response: in Applications
Share
January 15, 2011 8:23:44 PM

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.
a b L Programming
January 16, 2011 2:08:09 AM

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
  1. SERVICE_NAME: wuauserv
  2. DISPLAY_NAME: Windows Update
  3. TYPE : 20 WIN32_SHARE_PROCESS
  4. STATE : 4 RUNNING
  5. (STOPPABLE, NOT_PAUSABLE, ACCEPTS_PRESHUTDOWN)
  6. WIN32_EXIT_CODE : 0 (0x0)
  7. SERVICE_EXIT_CODE : 0 (0x0)
  8. CHECKPOINT : 0x0
  9. WAIT_HINT : 0x0
If you want to know if it's running:
  1. 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:
  1. sc <start|stop> wuauserv

m
0
l
January 17, 2011 12:13:03 AM

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?
m
0
l
a b L Programming
January 17, 2011 7:31:13 AM

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

m
0
l
!