How to check whether a specific service exists using Powershell?
Matthew Harrington
Introduction
According to this documentation it is possible to check which services have been stopped on Windows by executing the following command:
Get-Service | Where-Object {$_.status -eq "stopped"}
in PowerShell.
Question
Which command needs to be issued in PowerShell in order to check whether a certain service, e.g. tomcat8 exists?
3 Answers
You can specify the service name using the -Name attribute. By default if it doesn't see a matching service it will give an error. Using -ErrorAction SilentlyContinue you can get an empty variable back.
$service = Get-Service -Name W32Time -ErrorAction SilentlyContinueOnce you have that you can just see if the length is greater than 0.
if ($service.Length -gt 0) { # Do cool stuff } 1 This is a slightly cleaner solution than the accepted answer:
$service = Get-Service -Name MSSQLSERVER -ErrorAction SilentlyContinue
if($service -eq $null)
{ # Service does not exist
} else { # Service does exist
}In my opinion, checking it for NULL makes more sense semantically than checking for the length property.
This is tested and working in this version of PowerShell:
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 0 3 I cannot speak to other versions of PowerShell, but please comment if you have issues.
10Providing the service DHCP in fact exists, using $(Get-Service dhcp) -eq $null will return false. However, $(Get-Service dhcp) -ne $null will return true
1