Recipe 7.1. Starting and Stopping a ServiceProblemYou want to start or stop a service. SolutionUsing a graphical user interface
Using a command-line interface:Run any of the following commands to start a service: > psservice start <ServiceName> > sc start <ServiceName> > wmic service <ServiceName> call StartService > net start <ServiceName> Run any of the following commands to stop a service: > psservice stop <ServiceName> > sc stop <ServiceName> > wmic service <ServiceName> call StopService > net stop <ServiceName> You can use the wmic, psservice, and sc commands against a remote server. Using VBScript' This code stops and starts (effectively restarts) a service. ' ------ SCRIPT CONFIGURATION ------ strComputer = "<ServerName>" ' e.g., fs-rtp01 (use . for local server) strSvcName = "<ServiceName>" ' e.g., dnscache ' ------ END CONFIGURATION --------- set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") set objService = objWMI.Get("Win32_Service.Name='" & strSvcName & "'") intRC = objService.StopService WScript.Sleep 5000 ' Give the service 5 seconds to stop if intRC > 0 then WScript.Echo "Error stopping service: " & intRC else WScript.Echo "Successfully stopped service" end if intRC = objService.StartService if intRC > 0 then WScript.Echo "Error starting service: " & intRC else WScript.Echo "Successfully started service" end if DiscussionStarting and stopping a service is a straightforward procedure that every administrator has to do at one point or another. The only potentially tricky thing you need to be aware of when it comes to stopping a service is service dependencies. For example, if ServiceA depends on ServiceB and both services are currently running, you can't stop ServiceB unless you first stop ServiceA (the service that is dependent on it). If you are using the Services snap-in or the command-line tools, they are nice enough to stop all dependent services if there are any (use the /y option with the net stop command). From VBScript, the process is more manual. You first need to look up the dependent services and stop them. You will, in fact, receive an error when you use the StopService method on a service that has active dependencies. For a more robust example that automates stopping dependent services from VBScript, see Recipe 7.14. See AlsoRecipe 7.10, MSDN: StartService Method of the Win32_Service Class, and MSDN: StopService Method of the Win32_Service Class |