I have the following powershell script to monitor all automatic services on a server. It has exclusions for specific services and some that contain a part of a name. This script runs as expected if run directly on the server to be monitored. However if creating the component monitor in SAM it will always return the result that all services are running even if that is not the case. Can someone help as to what I have wrong?
# Define services to exclude by exact display name
$servicesToExclude = @("Performance Logs and Alerts","Microsoft .NET Framework NGEN v4.0.30319_X86", "Microsoft .NET Framework NGEN v4.0.30319_X64","Google Update Service (gupdate)","Remote Registry","Software Protection","Windows Update","Microsoft Exchange Notifications Broker","Background Intelligent Transfer Service","Windows Biometric Service","Microsoft Edge Update Service (edgeupdate)","Volume Shadow Copy","BrSplService","Dropbox Update Service (dbupdate)","Downloaded Maps Manager","Net.Msmq Listener Adapter","Net.Pipe Listener Adapter","Net.Tcp Listener Adapter")
# Define partial names of services to exclude
$partialNamesToExclude = @("*Sync Host_*", "*Clipboard User Service_*", "*GoogleUpdater*")
$RunResults = New-Object System.Collections.Generic.List[System.Object]
# Get all services set to Automatic startup type
$services = Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $servicesToExclude -notcontains $_.DisplayName -and $partialNamesToExclude -notlike $_.DisplayName }
# Initialize a flag to track if any service is not running
$anyServiceNotRunning = $false
$nonRunningServices = @()
# Check each service and collect non-running services
foreach ($service in $services) {
if ($service.Status -ne 'Running') {
$anyServiceNotRunning = $true
$nonRunningServices += $service.DisplayName
}
}
# Check if any service is not running
if ($anyServiceNotRunning) {
Write-Host "Statistic: 1"
Write-Host "Message: Non-running services - $($nonRunningServices -join ', ')"
} else {
Write-Host "Statistic: 0"
Write-Host "Message: All services set to Automatic start are running."
}