How to check whether a specific service exists using Powershell?
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 SilentlyContinue
Once you have that you can just see if the length is greater than 0.
if ($service.Length -gt 0) {
# Do cool stuff
}
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.