I'm looking to work on a batch script to check if a number of services are running and if not start them, this is what i have so far to check if a particular service is running:
for /F "tokens=3 delims=: " %%H in ('sc query "service1" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
net start "service1"
)
However, Id like to modify this for loop to check if there are matches for other services such as "service2", "service3", "service4" and "service5" but I don't know how to go about doing this. Is it possible to include these matches in the same For loop?
Thank you
If you want to do that in one loop with FOR in a batch :
FOR /F "tokens=2,3 delims=: " %%H IN ('^(SC QUERY "Service1" ^& SC QUERY "Service2"^) ^| FINDSTR /C:"SERVICE_NAME" /C:" STATE" ') DO (IF NOT "%%H" == "" (IF "%%I" == "" SET LOCALV_SERV=%%H) & IF NOT "%%I" == "" (IF /I "%%I" NEQ "RUNNING" CALL NET START %%LOCALV_SERV%%))
We query multiple services at once by concatenation of multiple SC outputs and then use here FINDSTR ability to search for multiple strings at once to gain the service name plus the service state.
As suggested by @Compo, you should test for many other service states.
For your use case then, the command should be :
FOR /F "tokens=2,3 delims=: " %%H IN ('^(SC QUERY "Service1" ^& SC QUERY "Service2" ^& SC QUERY "Service3" ^& SC QUERY "Service4" ^& SC QUERY "Service5"^) ^| FINDSTR /C:"SERVICE_NAME" /C:" STATE" ') DO (IF NOT "%%H" == "" (IF "%%I" == "" SET LOCALV_SERV=%%H) & IF NOT "%%I" == "" (IF /I "%%I" NEQ "RUNNING" CALL NET START %%LOCALV_SERV%%))
Replace Service1, Service2, Service3, Service4, Service5 with the service names you want to target.
As @Compo states that late expansion with CALL might be not appropriate, here is the same script with delayed expansion explicitly enabled :
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "tokens=2,3 delims=: " %%H IN ('^(SC QUERY "Service1" ^& SC QUERY "Service2"^) ^| FINDSTR /C:"SERVICE_NAME" /C:" STATE" ') DO (IF NOT "%%H" == "" (IF "%%I" == "" SET LOCALV_SERV=%%H) & IF NOT "%%I" == "" (IF /I "%%I" NEQ "RUNNING" NET START !LOCALV_SERV!))
Here's an expansion of my answer, based upon the comments, which enables delayed expansion only where needed within the loop. This version also removes the reliance on %PATH%
, and %PATHEXT%
, and improves readability:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "SC=%SystemRoot%\System32\sc.exe"
Set "FS=%SystemRoot%\System32\findstr.exe"
For /F "Tokens=2-3 Delims=: " %%G In ('
(%SC% Query "Service1" ^&
%SC% Query "Service2" ^&
%SC% Query "Service3" ^&
%SC% Query "Service4" ^&
%SC% Query "Service5"^) 2^>NUL
^| %FS% /BIC:"SERVICE_NAME:" /C:" STATE "
') DO (
If Not "%%G" == "" If "%%H" == "" Set "LOCALV_SERV=%%G"
If Not "%%H" == "" If /I Not "%%H" == "RUNNING" (
SetLocal EnableDelayedExpansion
%SC% Start !LOCALV_SERV!
EndLocal
)
)