I want to perform the following actions via batch file:
Action--> Check if multiple services with their names having common word in them are running or not, such as following criteria's:
1) IF services name contain word "Demo Service"
2) IF services name contain word "Demo Mobile Service"
3) IF services name contain word "Demo StTime Service"
Action--> If all of the services are running, quit the batch!
Action--> If one or more services are not running, start the services one by one
I have a server with about 50 services on them, sample name of the services:
001122 Demo Service
001122 Demo Mobile Service
001252 Demo Service
001252 Demo Mobile Service
001252 Demo StTime Service
For some reasons (Resources being one of them) few of the services stop at any random time, So i need this script working until i get more resources.
I found bits and pieces and tried to compile them something as below.
@ECHO off
SETLOCAL EnableDelayedExpansion
set "SERVICE_NAME=Demo Service"
echo %SERVICE_NAME%
FOR /L %%G IN (1,1,100) DO (
set "SERVICE_NAME=%SERVICE_NAME%%%G"
echo Starting "!SERVICE_NAME!"
net start "!SERVICE_NAME!"
)
set "M_SERVICE_NAME=Demo Mobile Service"
echo %M_SERVICE_NAME%
FOR /L %%G IN (1,1,100) DO (
set "M_SERVICE_NAME=%M_SERVICE_NAME%%%G"
echo Starting "!M_SERVICE_NAME!"
net start "!M_SERVICE_NAME!"
)
set "ST_SERVICE_NAME=Demo StTime Service"
echo %ST_SERVICE_NAME%
FOR /L %%G IN (1,1,100) DO (
set "ST_SERVICE_NAME=%ST_SERVICE_NAME%%%G"
echo Starting "!ST_SERVICE_NAME!"
net start "!ST_SERVICE_NAME!"
)
1st problem, it tries to look for 100 services because of the FOR loop, 2nd it says invalid service name so I am not sure how to fix the lixe criteria. Can certain someone please help me with this batch file ?
Let's see. First, list all services with sc query state= all
which will give a long list of such items:
SERVICE_NAME: w32time
DISPLAY_NAME: Windows Time
TYPE : 20 WIN32_SHARE_PROCESS
STATE : 4 RUNNING
(STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
PID : 1064
FLAGS :
Now filter the list by DISPLAY_NAME:
, Demo
and Service
:
sc query state= all | findstr /r /c:"DISPLAY_NAME: .*Demo .*Service"
The output will be:
DISPLAY_NAME: 001122 Demo Service
DISPLAY_NAME: 001122 Demo Mobile Service
DISPLAY_NAME: 001252 Demo Service
DISPLAY_NAME: 001252 Demo Mobile Service
DISPLAY_NAME: 001252 Demo StTime Service
Now get the text after the first word and start the service.
The final code is:
@echo off
for /f "tokens=1*" %%a in ('
sc query state^= all ^| findstr /r /c:"DISPLAY_NAME: .*Demo .*Service"
') do net start "%%b"
To hide the messages use net start "%%b" 2>nul
.