Restart a service with -WhatIf
Win32_Service has the StopService and StartService methods. The script calls them with Invoke-CimMethod, as a simulation (-WhatIf) as long as $dryRun is $true.
$serviceName = 'Spooler'
# $true: simulation only. Set to $false to act for real.
$dryRun = $true
$filter = "Name = '{0}'" -f $serviceName
$service = Get-CimInstance -ClassName Win32_Service -Filter $filter
$stopParameters = @{
InputObject = $service
MethodName = 'StopService'
WhatIf = $dryRun
}
$stopResult = Invoke-CimMethod @stopParameters
if (-not $dryRun) {
$deadline = (Get-Date).AddSeconds(30)
do {
Start-Sleep -Seconds 1
$service = Get-CimInstance -ClassName Win32_Service -Filter $filter
} until ($service.State -eq 'Stopped' -or (Get-Date) -gt $deadline)
}
$startParameters = @{
InputObject = $service
MethodName = 'StartService'
WhatIf = $dryRun
}
$startResult = Invoke-CimMethod @startParameters
if (-not $dryRun) {
Write-Output -InputObject ('StopService: {0}, StartService: {1}' -f $stopResult.ReturnValue, $startResult.ReturnValue)
}
Warning: this script stops and restarts a service; a service that others depend on is refused (code 3), and the clients of the service are cut. Keep -WhatIf (here $dryRun = $true) until the target service is the right one. ReturnValue = 0 means the request is accepted, not that the service is already stopped: the loop therefore waits for the Stopped state. Locally, Restart-Service does the same in one command; the CIM methods are mostly useful remotely, without PowerShell Remoting.
Variant: remote
The Invoke-CimMethod calls then act on the server, through the session of the instance. In the wait loop, read $service again with the same session.
$cimSession = New-CimSession -ComputerName 'SERVER01'
try {
$cimParameters = @{
CimSession = $cimSession
ClassName = 'Win32_Service'
Filter = "Name = 'Spooler'"
}
$service = Get-CimInstance @cimParameters
# Same StopService / StartService sequence as above, with -WhatIf first
} finally {
Remove-CimSession -CimSession $cimSession
}