There are occasions where you might need to check the windows service using the batch file. For the example, you need to run a conditional script that triggered by Task Scheduler. In this article, I’ll suggest a tip on how to create a batch script that will check the windows service is running or not.
Open a notepad and copy-paste the following code. You need to change the “MyServiceName” with the service name that you want to check.
@echo off 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" ) ) exit
- @ECHO OFF ==> To hide the text
- for /F “tokens=3 delims=: ” %%H in (‘sc query “MyServiceName” ^|
findstr” STATE”‘) do ( ==> this line will query the service and find string “STATE” on the result. Tokenizes that line, and pulls out the 3rd token, which is the one containing the state of the service.
- if /I “%%H” NEQ “RUNNING” ( ==> condition where the service is running.
- exit ==> exit from batch file.
Don’t forget to save the files with an extension of .bat.