Page 1 of 1

Batch for restart a services

Posted: 01 Feb 2010 01:30
by kyosa
I have a win 2003 server that has a service going down quit often. Is it possible to make a batch that check this service end if it's down, then the script is restarting the service?

Re: Batch for restart a services

Posted: 01 Feb 2010 03:30
by aGerman
kyosa

You could use TASKLIST and FINDSTR to test if a process is running.
Notepad as an example:

Code: Select all

@echo off &setlocal
set "process=notepad.exe"
set "fullname=%SystemRoot%\notepad.exe"

:loop
tasklist|findstr /i /b /l /c:"%process%">nul||start "" "%fullname%"
ping -n 2 localhost>nul
goto loop


Regards
aGerman

Re: Batch for restart a services

Posted: 01 Feb 2010 13:59
by avery_larry
net start "name of the service" >nul 2>nul


That will attempt to start the service if it's not already running, and it'll just throw an error if it's already running (and the error will be supressed by the >nul 2>nul part).

Run it as often as you like (I'd use the task scheduler).

ALSO -- the service itself can be set to autorecover if it stops running.

And finally -- if you really want to check before trying to start the service:

net start | find /i "name of the service" >nul 2>nul || net start "name of the service"

Will only try to start the service if it isn't running. Not that this method WOULD match partial service names. Example: If you have a service called "network" and a service called "network help", then the service "network help" would be a match for a check on the service "network".

Re: Batch for restart a services

Posted: 01 Feb 2010 15:09
by aGerman
avery_larry

You are right. I misunderstood that kyosa asked for a service.

avery_larry wrote:net start | find /i "name of the service" >nul 2>nul || net start "name of the service"

Will only try to start the service if it isn't running. Not that this method WOULD match partial service names. Example: If you have a service called "network" and a service called "network help", then the service "network help" would be a match for a check on the service "network".


FINDSTR could match it using regular expressions. IMHO line start, three blanks in front of each name, line end.

Code: Select all

net start | findstr /r /i /c:"^   name of the service$" >nul || net start "name of the service"


Regards
aGerman