X

Detecting unusual CPU load in Powershell

We recently had a problem on a server since one of its services was randomly experiencing spikes in CPU load that required restarting the service. Such event was happening once in a while and only required a restart. While we were tracking the problem down, we needed a temporary solution that didn’t require us to manually restart the service. Luckily Powershell came to the rescue with a simple script:

$interval = 30 #seconds
$counterSample = Get-Counter '\Processor(_Total)\% Processor Time' -SampleInterval $interval
$avgLoad = $counterSample.CounterSamples.CookedValue
Write-Output "Average CPU load : $avgLoad"

The tricky thing is that we didn’t want to measure CPU load as an instant value because such service could need to use all available resources for a short period of time so we couldn’t simply check if CPU was running at 80 or 100%. The script above measures average CPU load within a provided interval that has been set to 30 seconds in the sample.

Then, based on $avgLoad value, you could decide how to behave. In our case, we simply restart the service and notify our administrators. We simply scheduled a script like that to run every 5 minutes.

This sample has been taken from the Internet I don’t get credit for it but I hope it could be useful for someone else.

TSST Staff: