How to check if windows service is running

Few days ago I got a task in which I need to restart multiple services in multiple windows servers. So I wrote a batch file which does the same. But I faced one problem and that is I had to check for the application URL and make sure its up and RUNNING before going for the next service in a different server, as both services were dependent on each other I had to write the below function to check status recursively before going for the start/stop of the next service. This services can be started from a single remote windows machine where the batch file resides. I have used wmic(Windows Management Instrumentation Command-line) to do it. Its usually comes bundled/prepacked in Windows servers. I have used Windows server Standard Edition 2003 here, So this wmic command should work in newer versions too.

If you dont have wmic installed in your machine, then someone can use “sc” as a alternative. but somehow I did not find it reliable at times.

Below is the batch script to check whether a application url in a remote server is up and RUNNING or not.

I use telnet to ping to the url if ping gets a success for 7seconds then I consider the url and application is up or Not.

I use this function to do rolling restart multiple services remotely from a different server when one service requires to be up and RUNNING before we go for the next service to be started.


start /min telnet.exe %servername% %port%
ping -n 7 localhost >nul 2>&1
REM echo searching for Open Telnet connections to port %servername%:%PORT%
REM echo Checking the Status of Application Url: %servername%:%PORT%
for /f "tokens=2" %%i in ('tasklist /nh^| find "telnet.exe"')  do (

rem echo Port:%PORT% on %servername% OPEN!
taskkill /F /PID %%i /T >nul 2>&1
Goto :EOF
echo Waiting for the Application on %servername% to Start...
Goto :EOF
:: %1 is the Remote Machine Name
:: %2 is null if attempting to start, is Re- if restarting
Set loop=0
:: Will check state 20 times, adjust as needed.
If %loop%==240 Goto NoStart
:: Wait 5 second for service to (Re-)start (can also use sleep utility)
:: adjust -w as needed units are milliseconds
:: echo Checking Status Again in 5Seconds.
Ping -n 1 -w 5000 >Nul
Call :CheckState
If NOT "%STATE%"=="OPEN" (set /a loop+=1) & Goto CheckLoop
Echo Application on %servername% is OPEN for Business.
Echo Unable to start Application on %servername% in 20 minutes
ECHO Please check the state of service manually.
Set ErrFlag=1
Goto :EOF


set %servername%:%PORT% with the original port number the application RUNNING and the servername where the application is RUNNING.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.