Here’s how you can check if a service is running in PowerShell. I am using Threat Locker in my example.
Option 1 – Using Get-Service
$serviceName = "ThreatLockerService"
$service = Get-Service -Name $serviceName
if ($service.Status -eq "Running") {
Write-Output "The service '$serviceName' is running."
} else {
Write-Output "The service '$serviceName' is not running."
}
Option 2 – Using Where-Object for Filtering
$serviceName = "ThreatLockerService"
if (Get-Service | Where-Object { $_.Name -eq $serviceName -and $_.Status -eq "Running" }) {
Write-Output "The service '$serviceName' is running."
} else {
Write-Output "The service '$serviceName' is not running."
}
Option 3 – One Liner
(Get-Service -Name "ThreatLockerService").Status -eq "Running" | ForEach-Object { Write-Output "The service is $($_ -eq $true ? 'running' : 'not running')." }
Discussion
I run into an issue while writing this code. The service is not in the list, and it throws out an error. Below is the code to handle the error in this case.
$serviceName = "ThreatLockerService"
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) {
$service = Get-Service -Name $serviceName
if ($service.Status -eq "Running") {
Write-Output "The service '$serviceName' is running."
} else {
Write-Output "The service '$serviceName' is not running."
}
} else {
Write-Output "The service '$serviceName' is not available."
}
No responses yet