Recipe 10.16. Starting and Stopping a Service


Problem

You want to start or stop a service.

Solution

Using a graphical user interface

  1. Open the Services snap-in.

  2. In the left pane, right click on the service and select Start or Stop.

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>

Using VBScript
' This code stops and starts (effectively restarts) a service. ' ------ SCRIPT CONFIGURATION ------ strComputer   = "<HostName>"   ' e.g. fs-rtp01 (use . for local system) 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 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

Discussion

Starting and stopping a service is a straightforward procedure that everyone has to do at one point or another. The only potentially tricky thing you need to be aware of is when you need to stop a service that has dependencies. For example, if ServiceA depends on ServiceB and both services are currently running, you can't stop ServiceB unless you stop ServiceA (the service that is dependent on it) first. If you are using the Services snap-in, it will stop all dependent services if there are any. From the command line, the process is more manual. You need first to look up the dependent services and stop them. The same applies to the scripting solution. You will receive an error when you use the StopService method on a service that has dependencies. See Recipe 10.21 for more on how to find service dependencies from the command line and VBScript.

See Also

MSDN: StartService Method of the Win32_Service Class, and MSDN: StopService Method of the Win32_Service Class



Windows XP Cookbook
Windows XP Cookbook (Cookbooks)
ISBN: 0596007256
EAN: 2147483647
Year: 2006
Pages: 408

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net