[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string[]]$Name, [int]$MinCount = 1, [int]$MaxMemoryMB = 0, [int]$MaxCpuSeconds = 0, [switch]$Json ) $ErrorActionPreference = 'Stop' $processes = @(Get-Process -Name $Name -ErrorAction SilentlyContinue) if ($processes.Count -lt $MinCount) { $message = "Process check failed: found $($processes.Count), expected at least $MinCount" if ($Json) { [pscustomobject]@{ Ok = $false; Message = $message; Count = $processes.Count } | ConvertTo-Json } else { Write-Host $message } exit 2 } $rows = foreach ($process in $processes) { $memory = [math]::Round($process.WorkingSet64 / 1MB, 1) $cpu = 0 try { $cpu = [math]::Round($process.CPU, 1) } catch { $cpu = 0 } [pscustomobject]@{ Name = $process.ProcessName Id = $process.Id MemoryMB = $memory CpuSeconds = $cpu } } $totalMemory = ($rows | Measure-Object -Property MemoryMB -Sum).Sum $maxCpu = ($rows | Measure-Object -Property CpuSeconds -Maximum).Maximum $status = 0 if ($MaxMemoryMB -gt 0 -and $totalMemory -gt $MaxMemoryMB) { $status = 1 } if ($MaxCpuSeconds -gt 0 -and $maxCpu -gt $MaxCpuSeconds) { $status = 1 } if ($Json) { $rows | ConvertTo-Json -Depth 3 } else { $rows | Format-Table -AutoSize Write-Host ("Processes: {0}, total memory: {1} MB" -f $rows.Count, $totalMemory) } if ($status -ne 0) { Write-Host 'WARNING: process thresholds exceeded' exit 1 } Write-Host 'OK' exit 0