Stopped automatic services across several servers
A single query, a filter evaluated on the server side and one session per machine: the servers are queried in parallel.
$computerName = 'SERVER01', 'SERVER02', 'SERVER03'
$cimSession = New-CimSession -ComputerName $computerName
try {
$cimParameters = @{
CimSession = $cimSession
ClassName = 'Win32_Service'
Filter = "StartMode = 'Auto' AND State = 'Stopped'"
}
Get-CimInstance @cimParameters |
Select-Object -Property PSComputerName, Name, DisplayName, ExitCode |
Sort-Object -Property PSComputerName, Name
} finally {
Remove-CimSession -CimSession $cimSession
}
PSComputerName shows the originating machine. If a server does not answer, New-CimSession writes an error and still returns the sessions of the other servers.
Reducing the noise
Some services start automatically and then stop by themselves once their work is done. They exit with code 0. To keep only abnormal stops, add a condition on ExitCode to the filter:
Filter = "StartMode = 'Auto' AND State = 'Stopped' AND ExitCode <> 0"
Starting a service
A StartService method exists on the class, but Invoke-CimMethod acts on the system: try it with -WhatIf first.
$service = Get-CimInstance -ClassName Win32_Service -Filter "Name = 'Spooler'"
$methodParameters = @{
InputObject = $service
MethodName = 'StartService'
WhatIf = $true
}
Invoke-CimMethod @methodParameters