Batch script that will check the windows service is running or not

1
22442

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.

Batch Script

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

Explanation

  • @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.
check service

Don’t forget to save the files with an extension of .bat.

1 COMMENT

  1. Hi I would like to stop the service if it started and start if its stopped.
    I used your script which works fine for starting so I have added a else but it doesn’t work.
    Can you help me please it would be very friendly 🙂

LEAVE A REPLY

Please enter your comment!
Please enter your name here