Managing System Services - Windows PowerShell for Administration: The Personal Trainer (2015)

Windows PowerShell for Administration: The Personal Trainer (2015)

Chapter 8. Managing System Services

Services provide key functions to workstations and servers. To manage system services on local and remote systems, you use the following commands:

· Get-Service Gets information about the services on a local or remote computer, including running and stopped services. You can specify services by their service names or display names, or you can pass in references to service objects to work with.

Get-Service [[-Name] ServiceNames] [AddlParams]
Get-Service -DisplayName ServiceNames [AddlParams]
Get-Service [-InputObject ServiceObjects] [AddlParams]

{AddlParams}
[-ComputerName ComputerNames] [-DependentServices] [-Exclude
ServiceNames] [-Include ServiceNames] [-ServicesDependedOn]

· Stop-Service Stops one or more running services. You can specify services by their service names or display names, or you can pass in references to service objects to work with. Services that can be stopped indicate this because the CanStop property is set to True. Further, you can stop only a service that is in a state where stopping is permitted.

Stop-Service [-Name] ServiceNames [AddlParams]
Stop-Service -DisplayName ServiceNames [AddlParams]
Stop-Service [-InputObject ServiceObjects] [AddlParams]

{AddlParams}
[-Include ServiceNames] [-Exclude ServiceNames] [-Force]
[-PassThru]

· Start-Service Starts one or more stopped services. You can specify services by their service names or display names, or you can pass in references to service objects to work with.

Start-Service [-Name] ServiceNames [AddlParams]
Start-Service -DisplayName ServiceNames [AddlParams]
Start-Service [-InputObject ServiceObjects] [AddlParams]

{AddlParams}
[-Include ServiceNames] [-Exclude ServiceNames] [-Force]
[-PassThru]

· Suspend-Service Suspends (pauses) one or more running services. While paused, a service is still running, but its execution is halted until it is resumed. You can specify services by their service names or display names, or you can pass in references to service objects to work with. Services that can be suspended indicate this because the CanPauseAndContinue property is set to True. Further, you can pause only a service that is in a state where pausing is permitted.

Suspend-Service [-Name] ServiceNames [AddlParams]
Suspend-Service -DisplayName ServiceNames [AddlParams]
Suspend-Service [-InputObject ServiceObjects] [AddlParams]

{AddlParams}
[-Exclude ServiceNames] [-Include ServiceNames] [-PassThru]

· Resume-Service Resumes one or more suspended (paused) services. If you reference a service that is not paused, the control change is ignored. You can specify services by their service names or display names, or you can pass in references to service objects to work with.

Resume-Service [-Name] ServiceNames [AddlParams]
Resume-Service -DisplayName ServiceNames [AddlParams]
Resume-Service [-InputObject ServiceObjects] [AddlParams]

{AddlParams}
[-Exclude ServiceNames] [-Include ServiceNames] [-PassThru]

· Restart-Service Stops and then starts one or more services. If a service is already stopped, it is started. You can specify services by their service names or display names, or you can pass in references to service objects to work with.

Restart-Service [-Name] ServiceNames [AddlParams]
Restart-Service -DisplayName ServiceNames [AddlParams]
Restart-Service [-InputObject ServiceObjects] [AddlParams]

{AddlParams}
[-Include ServiceNames] [-Exclude ServiceNames] [-Force]
[-PassThru]

· Set-Service Changes the properties or status of a service on a local or remote computer. Use the status to change the state of the service.

Set-Service [-Name] ServiceName [ | -InputObject ServiceObjects]
[-DisplayName DisplayName] [-Description Description]
[-StartupType {Automatic | Manual | Disabled}]
[-Status {Running | Stopped | Paused}] [-PassThru]
[-ComputerName ComputerNames]

· New-Service Creates a new Windows service in the registry and in the services database. Pass in a credential if required to create the service.

New-Service [-Credential CredentialObject] [-DependsOn
ServiceNames] [-Description Description] [-DisplayName
DisplayName] [-StartupType {Automatic | Manual | Disabled}]
[-Name] Name [-BinaryPathName] PathtoExeFile

With some of these commands, you can specify the name of the remote computer whose services you want to work with. To do this, use the –ComputerName parameter and then specify the NetBIOS name, IP address, or fully qualified domain name (FQDN) of the remote computer or computers that you want to work with. In some cases, you might want to specify the local computer as well as a remote computer. To reference the local computer, type the computer name, a dot (.), or “localhost”.

Viewing Configured Services

To get a list of all services configured on a system, type get-service at the command prompt. Using the –ComputerName parameter, you can specify a remote computer to work with, as shown in the following example and sample output:

get-service –computername server92

Status Name DisplayName

------ ---- -----------

Running ADWS Active Directory Web Services

Stopped AeLookupSvc Application Experience

Stopped ALG Application Layer Gateway Service

Running AppHostSvc Application Host Helper Service

Stopped AppIDSvc Application Identity

Running Appinfo Application Information

The –ComputerName parameter accepts multiple name values. You can check the status of services on multiple computers simply by entering the names of the computers to check in a comma-separated list as shown in the following example:

get-service –computername fileserver86, dcserver22, printserver31

Rather than type computer names each time, you can enter computer names on separate lines in a text file and then get the list of computer names from the text file, as shown in the following example:

get-service -computername (get-content c:\data\clist.txt)

Here, you get the list of remote computers to check from a file called CList.txt in the C:\Data directory.

When you are looking for a specific service, you can reference the service by its service name or display name. To match partial names, you can use wildcard characters as shown in the following example and sample output:

get-service –displayname *browser* –computername fileserver86


Status Name DisplayName
------ ---- -----------
Running Browser Computer Browser

Here, you look for all services where the display name includes the word browser.

Get-Service returns objects representing each service matching the criteria you specify. From previous examples and sample output, you can see that the standard output includes the Status, Name, and DisplayName properties. To view all of the available properties, you need to format the output as a list, as shown in the following example and sample output:

get-service -displayname *browser* -computername server12 | format-list *

Name : Browser
RequiredServices : {LanmanServer, LanmanWorkstation}
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
DisplayName : Computer Browser
DependentServices : {}
MachineName : .
ServiceName : Browser
ServicesDependedOn : {LanmanServer, LanmanWorkstation}
ServiceHandle : SafeServiceHandle
Status : Stopped
ServiceType : Win32ShareProcess
Site :
Container :

The output shows the exact configuration of the service. As an administrator, you will work with the following properties most often:

· Name/ServiceName The abbreviated name of the service. Only services installed on the system are listed here. If a service you need isn’t listed, you’ll need to install it.

· DisplayName The descriptive name of the service.

· Status The state of the service as Running, Paused, or Stopped.

· DependentServices Services that cannot run unless the specified service is running.

· ServicesDependedOn The services this service relies on to operate.

· Type The type of service and whether it is a shared process.

· MachineName The name of the computer the service is configured on. This property is available only when you use the –ComputerName property.

TIP When you are configuring services, it is sometimes important to know whether a process runs in its own context or is shared. Shared processes are listed as WIN32SHAREPROCESS. Processes that run in their own context are listed as WIN32OWNPROCESS.

By default, Get-Service looks at all services regardless of their status. With the Status property, you can work with services in a specific state, such as Stopped or Paused. Consider the following examples:

get-service | where-object {$_.status -eq "Running"}
get-service | where-object {$_.status -eq "Stopped"}

In the first example, you list all services that are running. In the second example, you list all services that are stopped.

Starting, Stopping, and Pausing Services

As an administrator, you’ll often have to start, stop, or pause Windows services. When you are working with an elevated, administrator PowerShell prompt, you can do this using the service-related cmdlets or the methods of the Win32_Service class. Examples using the service cmdlets follow:

Start a service:

start-service ServiceName
start-service –displayname DisplayName
get-service ServiceName | start-service

Pause a service:

suspend-service ServiceName
suspend-service –displayname DisplayName
get-service ServiceName | suspend-service

Resume a paused service:

resume-service ServiceName
resume-service –displayname DisplayName
get-service ServiceName | resume-service

Stop a service:

stop-service ServiceName
stop-service –displayname DisplayName
get-service ServiceName | stop-service

In this example, ServiceName in each case is the abbreviated name of a service, and DisplayName is the descriptive name of a service, such as

stop-service –displayname "DNS Client"

Although Start-Service, Suspend-Service, Resume-Service, and Stop-Service don’t support the –ComputerName parameter, you can use the following technique to manage the state of services on remote computers:

get-service dnscache -computername engpc18 | stop-service
get-service dnscache -computername engpc18 | start-service

invoke-command -computername engpc18 –scriptblock
{get-service dnscache | stop-service }

invoke-command -computername engpc18 –scriptblock
{get-service dnscache | start-service }

Here, you use Get-Service to get a Service object on a remote computer, and then you manage the service using Start-Service, Suspend-Service, Resume-Service, or Stop-Service as appropriate. Note that these commands report only failure. They won’t tell you that the service was already started, stopped, paused, or resumed.

Before you stop or pause a service, you should check to see if the service can be stopped or paused. With Service objects, the properties you can check are CanPauseAndContinue and CanStop. An example and sample output follow:

$sname = read-host "Enter service name to stop"
$cname = read-host "Enter computer to work with"

$s = get-service $sname -computername $cname
if ($s.CanStop -eq $True) { $s | stop-service }


Enter service name to stop : dnscache
Enter computer to work with : engpc85

Here, you get the name of the service and computer to work with by prompting the user, and then you get the related Service object. If the service can be stopped, you stop the service. As shown in the following example and sample output, you can easily extend this basic functionality to perform other actions on services:

$cname = read-host "Enter computer to work with"
$sname = read-host "Enter service name to work with"

$s = get-service $sname -computername $cname
write-host "Service is:" $s.status -foregroundcolor green

$action = read-host "Specify action [Start|Stop|Pause|Resume]"

switch ($action) {

"start" { $s | start-service }
"stop" { if ($s.CanStop -eq $True) { $s | stop-service } }
"pause" { if ($s.CanPauseAndContinue -eq $True) { $s | pause-service } }
"resume" { $s | resume-service }

}

$su = get-service $sname -computername $cname
write-host "Service is:" $su.status -foregroundcolor green

Enter computer to work with: techpc12
Enter service name to work with: dnscache
Service is: Running
Specify action [Start|Stop|Pause|Resume]: stop
Service is: Stopped

Here, you get the name of the service and computer to work with by prompting the user, and then you get the related Service object. Next, you display the current status of the service and then get the action to perform on the service. After performing CanStop and CanPauseAndContinue tests if appropriate and taking the appropriate action on the service, you display the updated status of the service.

REAL WORLD Want to manage services any time you are working with PowerShell? Wrap this code in a function, and add it to your profile. Then you can manage services simply by calling the function. Here is an example:

function ms {
#Insert code here
}

Now any time your profile is loaded and you type ms at the PowerShell prompt, you’ll be able to manage services on any computer in the enterprise.

Configuring Service Startup

You can set Windows services to start manually or automatically. You also can turn services off permanently by disabling them. You configure service startup using

set-service ServiceName -StartupType Type [-ComputerName ComputerNames]

or

set-service -displayname DisplayName -StartupType Type
[-ComputerName ComputerNames]

where ServiceName or DisplayName identifies the service to modify, Type is the startup type to use, and ComputerNames are the names of the computers to work with. The valid startup types are:

· Automatic Starts a service at system startup. If the service requires a delayed start, the subtype Automatic (Delayed Start) is assigned automatically.

· Manual Allows the service to be started manually by the service control manager when a process invokes the service.

· Disable Disables the service to prevent it from being started the next time the computer is started. If the service is running, it will continue to run until the computer is shut down. You can stop the service if necessary.

Following this, you can configure a service to start automatically by using

set-service dnscache –startuptype automatic

or

set-service dnscache –startuptype automatic –computername techpc85

Instead of typing a comma-separated list of computer names, you can enter computer names on separate lines in a text file and then get the list of computer names from the text file as shown in the following example:

set-service dnscache –startuptype automatic –computername
(get-content c:\data\clist.txt)

Here, you get the list of remote computers to work with from a file called CList.txt in the C:\Data directory.

Set-Service also lets you start, stop, and pause services. If you are enabling a service on multiple computers, you also might want to start the service. You can enable and start a service as shown in the following example:

set-service w3svc –startuptype automatic –status running

If you are disabling a service on multiple computers, you also might want to stop the service. You can disable and stop a service as shown in the following example:

set-service w3svc –startuptype disabled –status stopped

Managing Service Logon and Recovery Modes

Occasionally, you might need to manage service logon and recovery options. The easiest way to do this is to use the Services Configuration utility. This utility has several subcommands that allow you to work with Windows services. The executable for this utility is sc.exe. Although you normally can type sc at the prompt and run this utility, sc is a default alias for Set-Content in Windows PowerShell. For this reason, you must type sc.exe whenever you work with this utility at the PowerShell prompt.

Configuring Service Logon

Using the SC config command, you can configure Windows services to log on as a system account or as a specific user. To ensure a service logs on as the LocalSystem account, use

sc.exe ComputerName config ServiceName obj= LocalSystem

where ComputerName is the Universal Naming Convention (UNC) name of the computer to work with, and ServiceName is the name of the service you are configuring to use the LocalSystem account. If the service provides a user interface that can be manipulated, add the flags type= interact type= own, as shown in the following example:

sc.exe config vss obj= LocalSystem type= interact type= own

or

sc.exe \\techpc85 config vss obj= LocalSystem type= interact type= own

NOTE You must include a space after the equal sign (=) as shown. If you don’t use a space, the command will fail. Note also these commands report only SUCCESS or FAILURE. They won’t tell you that the service was already configured in a specified way.

Thetype= interact flag specifies that the service is allowed to interact with the Windows desktop. The type= own flag specifies that the service runs in its own process. In the case of a service that shares its executable files with other services, you use the type= share flag, as shown in this example:

sc.exe config dnscache obj= LocalSystem type= interact type= share

TIP If you don’t know whether a service runs as a shared process or in its own context, you should determine the service’s start type using Get-Service.

Services can also log on using named accounts. To do this, use

sc.exe config ServiceName obj= [Domain\]User password= Password

where Domain is the optional domain name in which the user account is located, User is the name of the user account whose permissions you want to use, and Password is the password of that account. Consider the following example:

sc.exe config vss obj= adatum\backers password= TenMen55!

Here, you configure Microsoft Visual SourceSafe (VSS) to use the Backers account in the Adatum domain. The output of the command should state SUCCESS or FAILED. The change will fail if the account name is invalid or doesn’t exist, or if the password for the account is invalid.

NOTE If a service has been previously configured to interact with the desktop under the LocalSystem account, you cannot change the service to run under a domain account without using the type= own flag. The syntax therefore becomes sc config ServiceName obj= [Domain\]User password= Password type= own.

Although SC is designed to work with individual computers, you can use the built-in features of Windows PowerShell to modify the way SC works, as shown in the following example:

$c = "\\techpc85"
sc.exe $c query dnscache

Here, rather than specifying the computer name explicitly, you pass in the computer name as a variable.

You can extend this basic technique to get a list of remote computers to work with from a file. Here is an example:

$computers = (get-content c:\data\unclist.txt)
foreach ($c in $computers) { sc.exe $c query dnscache }

Here, you get the list of computers to work with from a file called UncList.txt in the C:\Data directory and then execute an SC query for each computer name.

TIP Don’t forget that SC requires computer names to be specified using Universal Naming Convention. This means you must type \\techpc85 rather than techpc85 in the text file from which computer names are obtained.

Configuring Service Recovery

Using the SC Qfailure and Failure commands, you can view and configure actions taken when a service fails. For example, you can configure a service so that the service control manager attempts to restart it or to run an application that can resolve the problem.

You can configure recovery options for the first, second, and subsequent recovery attempts. The current failure count is incremented each time a failure occurs. You can also set a parameter that specifies the time that must elapse before the failure counter is reset. For example, you can specify that if 24 hours have passed since the last failure, the failure counter should be reset.

Before you try to configure service recovery, check the current recovery settings using SC Qfailure. The syntax is

sc.exe ComputerName qfailure ServiceName

where ComputerName is the UNC name of the computer to work with, and ServiceName is the name of the service you want to work with, such as

sc.exe qfailure adws

or

sc.exe \\techpc85 qfailure adws

In the output, the failure actions are listed in the order they are performed. In the following example output, ADWS is configured to attempt to restart the service the first and second times the service fails:

[SC] QueryServiceConfig2 SUCCESS

SERVICE_NAME: adws

RESET_PERIOD (in seconds) : 900

REBOOT_MESSAGE :

COMMAND_LINE :

FAILURE_ACTIONS : RESTART -- Delay = 120000 milliseconds.

RESTART -- Delay = 300000 milliseconds.

NOTE Windows automatically configures recovery for some critical system services during installation. Typically, these services are configured so that they attempt to restart the service. A few are configured to restart the server if they fail. Services also can be configured so that they run programs or scripts upon failure.

The command you use to configure service recovery is SC Failure, and its basic syntax is

sc.exe failure ServiceName reset= FailureResetPeriod actions=
RecoveryActions

where ServiceName is the name of the service you are configuring; FailureResetPeriod specifies the time, in seconds, that must elapse without failure in order to reset the failure counter; and RecoveryActions are the actions to take when failure occurs plus the delay time (in milliseconds) before that action is initiated. The available recovery actions are:

· Take No Action (indicated by an empty string “”) The operating system won’t attempt recovery for this failure but might still attempt recovery of previous or subsequent failures.

· Restart The Service Stops and then starts the service after a brief pause.

· Run A Program Allows you to run a program or a script in case of failure. The script can be a batch program or a Windows script. If you select this option, set the full file path to the program you want to run, and then set any necessary command-line parameters to pass in to the program when it starts.

· Reboot The Computer Shuts down and then restarts the computer after the specified delay time has elapsed.

NOTE When you configure recovery options for critical services, you might want to try to restart the service on the first and second attempts and then reboot the server on the third attempt.

When you work with SC Failure, keep the following in mind:

· The reset period is set in seconds.

Reset periods are commonly set in multiples of hours or days. An hour is 3,600 seconds, and a day is 86,400 seconds. For a two-hour reset period, for example, you’d use the value 7,200.

· Each recovery action must be followed by the time to wait (in milliseconds) before performing the action.

For a service restart, you’ll probably want to use a short delay, such as 1 millisecond (no delay), 1 second (1,000 milliseconds), or 5 seconds (5,000 milliseconds). For a restart of the computer, you’ll probably want to use a longer delay, such as 15 seconds (15,000 milliseconds) or 30 seconds (30,000 milliseconds).

· Enter the actions and their delay times as a single text entry, with each value separated by a forward slash (/).

For example, you could use the following value: restart/1000/restart/1000/reboot/15000. Here, on the first and second attempts the service is restarted after a 1-second delay, and on the third attempt the computer is rebooted after a 15-second delay.

Consider the following examples:

sc.exe failure w3svc reset= 86400 actions=
restart/1/restart/1/reboot/30000

Here, on the first and second attempts the service is restarted almost immediately, and on the third attempt the computer is rebooted after a 30-second delay. In addition, the failure counter is reset if no failures occur in a 24-hour period (86,400 seconds). You can also specify a remote computer by inserting the UNC name or IP address as shown in previous examples.

If you use the Run action, you specify the command or program to run using the Command= parameter. Follow the Command= parameter with the full file path to the command to run and any arguments to pass to the command. Be sure to enclose the command path and text in double quotation marks, as in the following example:

sc.exe failure w3svc reset= 86400 actions=
restart/1/restart/1/run/30000 command= "c:\restart_w3svc.exe 15"

Digging Deeper into Service Management

Although the Get-Service cmdlet provides sufficient details to help you perform many administrative tasks, it doesn’t provide the detailed information you might need to know to manage the configuration of services. At a minimum, to manage service configuration, you need to know a service’s current start mode and start name. The start mode specifies the startup mode of the service, and the start name specifies the account name under which the service will run. A service’s start mode can be set to any of the following:

· Automatic Indicates the service is started automatically by the service control manager during startup of the operating system.

· Manual Indicates the service is started manually by the service control manager when a process calls the StartService method.

· Disabled Indicates the service is disabled and cannot be started.

Most services run under one of the following accounts:

· NT Authority\LocalSystem LocalSystem is a pseudo account for running system processes and handling system-level tasks. This account is part of the Administrators group on a computer and has all user rights on the computer. If services use this account, the related processes have full access to the computer. Many services run under the LocalSystem account. In some cases, these services have the privilege to interact with the desktop as well. Services that need alternative privileges or logon rights run under the LocalService or NetworkService accounts.

· NT Authority\LocalService LocalService is a pseudo account with limited privileges. This account grants access to the local system only. The account is part of the Users group on the computer and has the same rights as the NetworkService account, except that it is limited to the local computer. If services use this account, the related processes don’t have access to other computers.

· NT Authority\NetworkService NetworkService is a pseudo account for running services that need additional privileges and logon rights on a local system and the network. This account is part of the Users group on the computer and provides fewer permissions and privileges than the LocalSystem account (but more than the LocalService account). Specifically, processes running under this account can interact throughout a network using the credentials of the computer account.

You can obtain the start mode, start name, and other configuration information for services using Windows Management Instrumentation (WMI) and the Win32_Service class. You use the Win32_Service class to create instances of service objects as they are represented in WMI.

By typing get-wmiobject -class win32_service you can list all services configured on a computer, as shown in the following example and sample output:

get-wmiobject -class win32_service | format-table name, startmode, state, status

name startmode state status
---- --------- ----- ------
ADWS Auto Running OK
AeLookupSvc Manual Stopped OK
ALG Manual Stopped OK
AppHostSvc Auto Running OK
AppIDSvc Manual Stopped OK
Appinfo Manual Running OK
AppMgmt Manual Stopped OK
AppReadiness Manual Stopped OK
AppXSvc Manual Stopped OK
aspnet_state Manual Stopped OK
Audiosrv Manual Stopped OK
AxInstSV Manual Stopped OK
BFE Auto Running OK
BITS Manual Stopped OK
Browser Disabled Stopped OK
CertPropSvc Manual Running OK
COMSysApp Manual Stopped OK
CryptSvc Auto Running OK
CscService Disabled Stopped OK

If you want to work with a specific service or examine services with a specific property value, you can add the –Filter parameter. In the following example and sample output, you check the configuration details of the Browser service:

get-wmiobject -class win32_service -filter "name='browser'"


ExitCode : 1077
Name : Browser
ProcessId : 0
StartMode : Disabled
State : Stopped
Status : OK

If you format the output as a list, you’ll see additional configuration information including PathName, which specifies the executable that starts the service and any parameters passed to this executable, and StartName, which specifies the account under which the service runs. In the following example and partial output, you examine the properties of the DNS Client service:

$s = get-wmiobject -class win32_service -filter "name='dnscache'"
$s | format-list *

Name : Dnscache
Status : OK
ExitCode : 0
DesktopInteract : False
ErrorControl : Normal
PathName : C:\Windows\system32\svchost.exe –k
NetworkService
ServiceType : Share Process
StartMode : Auto
AcceptPause : False
AcceptStop : True
Caption : DNS Client
CheckPoint : 0
CreationClassName : Win32_Service
Description : The DNS Client service (dnscache)
caches Domain Name System (DNS) names
DisplayName : DNS Client
InstallDate :
ProcessId : 332
ServiceSpecificExitCode : 0
Started : True
StartName : NT AUTHORITY\NetworkService
State : Running
SystemCreationClassName : Win32_ComputerSystem
SystemName : CORPSERVER64

Get-WmiObject supports a –ComputerName parameter that lets you specify the remote computer or computers to work with, as shown in these examples:

get-wmiobject -class win32_service –computername fileserver86,
dcserver22, printserver31

get-wmiobject -class win32_service -computername (get-content
c:\data\clist.txt)

NOTE When you are working with multiple computers, you can use the SystemName property to help you determine the name of the computer the service is configured on.

You can work with the properties of Win32_Service objects in much the same way as you work with properties of Service objects. To see a list of all services configured to start automatically, you can type the following command:

get-wmiobject -class win32_service -filter "startmode='auto'" |
format-table name, startmode, state, status

To view all running services, you can type

get-wmiobject -class win32_service -filter "state='running'" |
format-table name, startmode, state, status

The Win32_Service class provides a number of methods for managing system services. These methods include:

· Change() Changes the configuration of a user-configurable service. This method accepts the following parameters in the following order: DisplayName, PathName, ServiceTypeByte, ErrorControlByte, StartMode, DesktopInteractBoolean, StartName, StartPassword, LoadOrderGroup, LoadOrderGroupDependenciesArray, and ServiceDependenciesArray.

CAUTION Not all services can be reconfigured. Modifying services at the PowerShell prompt is not something you should do without careful forethought. PowerShell will let you make changes that could put your computer in an unstable state. Before you make any changes to services, you should create a system restore point as discussed in Chapter 9, “Managing Computer Accounts.”

· ChangeStartMode() Changes the start mode of a user-configurable service. This method accepts a single parameter, which is the start mode to use. Valid values are Manual, Automatic, or Disabled.

NOTE Some services are configured by default to use delayed-start automatic mode. When you are working with Win32_Service, any time you set these services to Automatic, they use delayed-start automatic mode. Additionally, note that disabling a service doesn’t stop a running service. It only prevents the service from being started the next time the computer is booted. To ensure that the service is disabled and stopped, disable and then stop the service.

CAUTION Before you change the start mode of a service, you should check dependencies and ensure any changes you make won’t affect other services.

· Delete() Deletes a user-configurable service (if the service is in a state that allows this). Rather than delete a service, you should consider disabling it. Disabled services no longer run and can easily be enabled if needed in the future. Deleted services, however, must be reinstalled to be used in the future.

CAUTION Exercise extreme caution if you plan to delete services using PowerShell. PowerShell will not warn you if you are making harmful changes to your computer.

· InterrogateService() Connects to the service using the service control manager. If the return value is zero, the service control manager was able to connect to and interrogate the service using its configured parameters. If the return value wasn’t zero, the service control manager encountered a problem while trying to communicate with the service using the configured parameters. If the service is stopped or paused, this method will always return an error status.

· PauseService() Pauses the service, which might be necessary during troubleshooting or when performing diagnostics. Services that can be paused indicate this by setting the AcceptPause property to True for their services. Further, you can pause only a service that is in a state where pausing is permitted.

· ResumeService() Resumes the service after it has been paused.

· StopService() Stops the service, which might be necessary during troubleshooting or when performing diagnostics. Services that can be stopped indicate this by setting the AcceptStop property to True for their services. Further, you can stop only a service that is in a state where stopping is permitted.

· StartService() Starts a stopped service, including services that are configured for manual startup.

When you are working with an elevated, administrator PowerShell prompt, you can use these methods to manage system services. For example, you can set Windows services to start manually or automatically. You can also turn them off permanently by disabling them. You configure service startup using the ChangeStartMode() method to specify the desired start mode. The basic syntax is

$serviceObject.ChangeStartMode(StartMode)

where $serviceObject is a reference to a Win32_Service object, and StartMode is the desired start mode entered as a string value, as shown in this example and sample output:

$s = get-wmiobject -class win32_service –filter "name='dnscache'"

$s.changestartmode("automatic")

__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0

Here, you set the start mode to Automatic. The return value in the output is what you want to focus on. A return value of 0 indicates success. Any other return value indicates an error. Typically, errors occur because you aren’t using an elevated, administrator PowerShell prompt, you haven’t accessed the correct service, or the service isn’t in a state in which it can be configured. Keep in mind that if you alter the configuration of required services, the computer might not work as expected. Because of this, don’t make any changes to services without careful planning and forethought.

NOTE These commands report only SUCCESS or FAILURE. They won’t tell you that the service was already started, stopped, or configured in the startup mode you’ve specified.

A technique for invoking methods of WMI objects we haven’t discussed previously is using a direct invocation using the Invoke-WMIMethod cmdlet. This cmdlet provides a one-line alternative to the two-line technique that requires you to get a WMI object and then invoke its method. For example, instead of using

$s = get-wmiobject -class win32_service
–filter "name='dnscache'"

$s.stopservice()

you can use

invoke-wmimethod -path "win32_service.name='dnscache'"
-name stopservice

Syntax options for Invoke-WmiMethod include the following:

Invoke-WmiMethod [-ComputerName [ComputerNames]] [-Credential
[CredentialObject]] [-Name] [MethodName] [-ThrottleLimit
[LimitValue]] [-AsJob]

Invoke-WmiMethod [-InputObject [WMIObject]] [-Name] [MethodName]
[-ThrottleLimit [LimitValue]] [-AsJob]

Invoke-WmiMethod [-Namespace [WMINamespace]] -Path [WMIPath]
[-ArgumentList [Objects] [-Name] [MethodName] [-ThrottleLimit
[LimitValue]] [-AsJob]

Invoke-WmiMethod [-EnableAllPrivileges] [-Authority [Authority]]
[-Name] [MethodName] [-ThrottleLimit [LimitValue]] [-AsJob]

Invoke-WmiMethod [-Locale [Locale]] [-Name] [MethodName]
[-ThrottleLimit [LimitValue]] [-AsJob]

You can use the methods of the Win32_Service class and Invoke-WmiMethod to manage services as shown in the following examples:

Start a service:

invoke-wmimethod -path "win32_service.name='ServiceName'"
-name startservice

invoke-wmimethod -path "win32_service.displayname='DisplayName'"
-name startservice

get-wmiobject -class win32_service -filter "name='ServiceName'" |
invoke-wmimethod -name startservice

Pause a service:

invoke-wmimethod -path "win32_service.name='ServiceName'"
-name pauseservice

invoke-wmimethod -path "win32_service.displayname='DisplayName'"
-name pauseservice

get-wmiobject -class win32_service -filter "name='ServiceName'" |
invoke-wmimethod -name pauseservice

Resume a paused service:

invoke-wmimethod -path "win32_service.name='ServiceName'"
-name resumeservice

invoke-wmimethod -path "win32_service.displayname='DisplayName'"
-name resumeservice

get-wmiobject -class win32_service -filter "name='ServiceName'"
| invoke-wmimethod -name resumeservice

Stop a service:

invoke-wmimethod -path "win32_service.name='ServiceName'"
-name stopservice

invoke-wmimethod -path "win32_service.displayname='DisplayName'"
-name stopservice

get-wmiobject -class win32_service -filter "name='ServiceName'"
| invoke-wmimethod -name stopservice

Before you stop or pause a service, you should check to see if the service can be stopped or paused. With Win32_Service objects, the properties you can check are AcceptPause and AcceptStop.

You can use the techniques discussed previously to work with services when Get-WmiObject returns a single matching Win32_Service object. However, these techniques won’t work as expected when Get-WmiObject returns multiple Win32_Service objects. The reason for this is that the objects are stored in an array, and you must specify the instance within the array to work with. One technique for doing so is shown in the following example and partial output:

$servs = get-wmiobject -class win32_service |
where-object {$_.name -match "client"}

foreach ($s in $servs) { $s.changestartmode("automatic") }

ReturnValue : 0

ReturnValue : 0

ReturnValue : 0

Here, three Win32_Service objects were returned, and each was set to start automatically. This technique will work when there is only one matching service as well.