Scheduled BAT file to check if a Service has Stopped / Restart if Stopped
Sometimes services will stop without our control, which can cause the knock on affect of bringing your whole system to a halt. The best example of this is if our NAV Webservice or NAS Application Server Service stops this may stop other processes as a knock on effect. To get around this we can create a Scheduled task which will check to see if our specified service has stopped. If it has - it will restart it automatically for you.
If the service is in a 'Running' state the scheduled BAT file will Quit.
If the service is in a 'Stopped' state the scheduled BAT file will Restart the service.
1. The First thing to do is create the BAT file. This can be done by doing the following.
- Open Notepad
- Add the below code
- Insert the relevant Service name where it says 'MyServiceName'
Note: This can be found from 'services.msc' - right click the service, Properties - Service Name.
- Save the text file as a .BAT file. >> Sales As >> Save As Type (All Files) >>Filename = ExampleName.BAT >> Save
Note: You can test the BAT file by stopping the relevant service and 'running' the BAT file with admin privileges.
for /F "tokens=3 delims=: " %%H in ('sc query "MyServiceName" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
REM Put your code you want to execute here
REM For example, the following line
net start "MyServiceName"
)
)
source
lc. - Stack Overflow
1. We can now create a Scheduled Task >> Control Panel >> Administrative Tools >> Schedule Tasks
2. This is your task scheduler screen >> Click 'Create Task....' or right click the Task Scheduler tab and 'Create Task...'
3. A new window will appear 'Create Task' and will default to the General Tab. Give your Schedule a name and a description. Also select the following -
- 'Run whether user is logged on or not'
- 'Run with highest Privileges'.
4.Triggers Tab >> New... >> Choose the frequency of the schedule. I have chosen every five minutes until the end of time. >> Tick the 'Enabled' flag.
5. Lastly you need to select the 'Actions' tab on the Create Task screen. You will need to select the .BAT file you created. This should be saved somewhere accessible - C:\bat files etc. >> Once selected - press ok and check the Task has been created.
Note: Using my user accounts desktop is not a good example as this will potentially be locked down to other windows users. The root of C is the best bet.
Andy
and you can add an event to the event log if you want that this service has restarted:
ReplyDeleteeventcreate /ID 1 /L APPLICATION /T WARNING /SO "[Event Source]" /D "[Message]"
Enter your Event Source (e.g.: Service Restarter) and the Message (e.g.: MyServiceName has restarted because it wasn't running)