Recipe7.1.Starting and Stopping a Service


Recipe 7.1. 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 right 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>

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

Discussion

Starting 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 Also

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



Windows Server Cookbook
Windows Server Cookbook for Windows Server 2003 and Windows 2000
ISBN: 0596006330
EAN: 2147483647
Year: 2006
Pages: 380
Authors: Robbie Allen

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