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 ...

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.