A frequent issue on servers is when services that are supposed to start simply haven’t started.
There’s a simple one-liner that can show you the services that meet these requirements for you:
1
|
Get-WmiObject -Class Win32_Service -Filter "Startmode = 'Auto' AND State = 'Stopped' AND ExitCode != 0"
|
Want to directly start up these services? Not a problem!
1
|
Get-WmiObject -Class Win32_Service -Filter "Startmode = 'Auto' AND State = 'Stopped' AND ExitCode != 0" | Start-Service
|
I prefer to make my solutions re-usable because well.. I’m lazy.
In case you have the same feeling, here’s the function I’ve created for this with some added functionality.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
function Get-AutoStartService {
<#
.SYNOPSIS
Display all the services which should start automatically, but have incorrectly stopped
.DESCRIPTION
Using WMI display all the services on a computer which have a StartMode of Auto, but are currently Stopped with an error code
.PARAMETER ComputerName
Provide the computer name of the machine[s] you would like to query.
Default value is the local machine
.PARAMETER Restart
A switch parameter, if included will try and automatically restart the services which are incorrectly stopped
Do note that this requires Admin privileges on the machine you are accessing
.NOTES
Name: Get-AutoStartService.ps1
author: Robert Prüst
DateCreated: 02-07-2015
.EXAMPLE
Get-AutoStartService -ComputerName localhost -Restart
#>
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$True)]
$ComputerName = $env:COMPUTERNAME ,
[switch]$Restart
)
$StoppedServices = Get-WmiObject -Class Win32_Service -ComputerName $ComputerName -Filter "StartMode = 'Auto' AND State = 'Stopped' AND ExitCode != 0"
Write-Output $StoppedServices
if (!$StoppedServices) {
Write-Output 'All services seem to be running as intended'
}
if ($Restart){
foreach ($StoppedService in $StoppedServices){
Write-Verbose "Starting Service $($StoppedService.Name)"
$StoppedService | Start-Service
Write-Output "Service $($StoppedService.Name) has been started again. Please re-run the Get-AutoStartService to see if it remains running"
Get-Service $($StoppedService.Name)
}
}
}
|
If you have any questions about the function, pieces of code used or perhaps tips [if you have any, please do share!!], let me know and leave a comment.
Happy scripting! 🙂