I’m a bit behind in posting some of this code. This was one of the projects a student brought to class. He needed to know how to use PowerShell to monitor if any processes consumed more than 25% of the processor time. If so, he had a set of services that needed to be restarted. Below is the code to find out the current processor load with the process restarting code commented out.
The get-counter cmdlet gave us the ability to collect multiple samples so that a spike would not trigger the process restart. In the code below, we took two samples with 1 second between them. Yes, the variable $CurrentLoad is set with a very long one liner.
Function CheckProcess
{
Param (
$Threshold = 25
)
$CurrentLoad = ((get-counter -counter "\processor(_total)\% Processor time" -SampleInterval 1 -MaxSamples 2) |
ForEach {$_.CounterSamples} |
Select-Object -Property CookedValue |
ForEach {$_.CookedValue} |
Measure-Object -Average).Average
If ($CurrentLoad -gt $Threshold)
{
# Kill Processes
# EX: "Proc1", "Proc2", "Proc3" | Stop-Process
# Pause script to allow processes to stop
Start-Sleep 1
# To Restart Service
# EX: "Service" | Restart-Server
}
}
CheckProcess
Comments