7.14. Script: Robust Service Restart

A service can be dependent on other services and have other services dependent on it. This is a nice feature because you can configure that in order for ServiceA to run, ServiceB needs to already be running. However, this makes things more complicated when it comes to stopping and starting services. If you want start ServiceA, you also need to make sure ServiceB is running.

When it comes to programmatically restarting services, you could just call the StopService and StartService methods on a service. And since a lot of services don't have any dependencies, this will generally work. But if you happen to try restarting a service that has a dependency, the restart will not be successful. The solution to this is to write a bit of code that can handle restarting services, regardless of dependencies. Here is the code:

' This code restarts a service by first stopping all
' dependent services before stopping the target service.
' Then the target service is started and then all dependent 
' services are started.
Option Explicit
Dim strComputer : strComputer = "."        ' e.g., fs-rtp01
Dim strSvcName  : strSvcName  = "<ServiceName>" ' e.g., dnscache ' ------ END CONFIGURATION --------- Dim objWMI : set objWMI = GetObject("winmgmts:\\" & strComputer & _ "\root\cimv2") Dim objService: set objService = objWMI.Get("Win32_Service.Name='" & _ strSvcName & "'") WScript.Echo "Restarting " & objService.Name & "..." RecursiveServiceStop ...

Get Windows Server Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.