Batch for restart a services

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
kyosa
Posts: 1
Joined: 01 Feb 2010 01:24

Batch for restart a services

#1 Post by kyosa » 01 Feb 2010 01:30

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?

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Batch for restart a services

#2 Post by aGerman » 01 Feb 2010 03:30

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

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

Re: Batch for restart a services

#3 Post by avery_larry » 01 Feb 2010 13:59

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".

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Batch for restart a services

#4 Post by aGerman » 01 Feb 2010 15:09

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

Post Reply