Create a batch file to check the status of a Windows Service(s) and start it if its not started. The batch file can also be run inside "Task Scheduler" at an interval basis.
1. First, you need to find out the Service Name that you want to monitor, in this example let's say the service you need to monitor is an Exchange Server IMAP4 service.
2. Open --> Services and browse through the list until you found the IMAP4 service.
3. Right-click the Service Name --> Properties.
4. Take note of the "Service name:", copy the name to Notepad. As per below screenshot, the service name is "MSExchangeImap4".
5. Create a batch file as below :-
@ECHO OFF CLS SETLOCAL ENABLEDELAYEDEXPANSION SET /A RETRY_IMAP=0 SET /A MAX_RETRIES=3 SET EXCH_IMAP= MSExchangeImap4 REM To check current status of the service. :check_imap SC QUERY %EXCH_IMAP% | FIND "RUNNING" >NUL IF %ERRORLEVEL%==0 ( ECHO Exchange IMAP4 Service is Running. GOTO end ) REM To start the service if the status is stopped. ECHO Exchange IMAP4 Service is Stopped. SC START %EXCH_IMAP% TIMEOUT /T 10 >NUL REM To re-check the service status again for confirmation. SC QUERY %EXCH_IMAP% | FIND "RUNNING" >NUL IF %ERRORLEVEL%==0 ( ECHO Exchange IMAP4 Service is Running. GOTO end ) REM Retrying to start the service with a maximum of 3 retries only. SET /A RETRY_IMAP+=1 IF !RETRY_IMAP! LSS %MAX_RETRIES% ( ECHO Retrying Start %EXCH_IMAP% (Attemp: !RETRY_IMAP!). GOTO check_imap ) ELSE ( ECHO Max Retries Reached for %EXCH_IMAP%, will stop retrying. GOTO end ) :end EXIT |
6. You can now test run the batch file and create a "Task Scheduler" to run the check at an interval basis (eg. every 2 hours or at Startup of the server).
!!! HAPPY COMPUTING !!!