18 windows services and stop service if exists and running and then next service. Request has been completed

I have a list of services that may or may not all exist on a windows server. I would like to check if the service exists and if running to stop that service and wait till stopped and then move to the next service which may not exist or is not running and if so skip and then move to the next service in the list. A service may stop other dependent services as well that could be in the list.
I have 18 CommVault services that are application such as commserve or media agent , but both could be on same server. So i would like to run through all 18 known services and if running stop that service and either skip the next if not there or is not running.

something like this. I am sure there is better way to form this as i am thinking waithidden would not move to next command until service stopped.

example

if { exists running service “service name”}
then service “service name” stop
else continue if {not exists running service “service name”}

if { exists running service “service name”}
then service “service name” stop
else continue if {not exists running service “service name”}

until finished.

Any thoughts

1 approach I can think of…for your fixlet relevance, check for any of the services being present, eg

exists services ("AdobeARMservice";"BITS";"DoesntExist";"Bonjour Service";"EpsonScanSvc";"DoesntExist2")

For the action, store the service name as a parameter concatenating each service name that exists to string that can then be passed to a CMD for loop that does a net stop for each service

parameter "ServiceList" = "{"%22" & (concatenation "%22 %22" of service names of services ("AdobeARMservice";"BITS";"DoesntExist";"Bonjour Service";"EpsonScanSvc";"DoesntExist2")) & "%22"}"
run cmd.exe /c "for %a in ({parameter "ServiceList"}) do net stop %a"

You may want to further tweak it so only services that are in a running state get stopped if your use case may have services that exist but already in a stopped state.

exists services ("AdobeARMservice";"BITS";"DoesntExist";"Bonjour Service";"EpsonScanSvc";"DoesntExist2") whose (state of it = "Running")

Suggest, you don’t actually need to know if the services exist.

You could stop all of them in a row and ignore any service stops that fail.

exists running services ("service1";"service2";"service3")

wait sc.exe stop service1
wait sc.exe stop service2
wait sc.exe stop service3

Very true @brolly33 :grin:

Thanks to everyone for your quick replies. Much appreciated. thanks SLB and Brolly. I have what i need.

2 Likes