PowerShell: Email on high CPU usage

Another quickie. The requirement was to get an email alert when CPU usage reached over 90%. This is achievable via PerfMon Data Collector Set alerts, EventLog task triggers and a script to send an email (unless you’re on pre-Server 2012 when you could send an email as an event log trigger directly – why was that option removed?).

But that’s a load of faff, whereas this script is tiny and easy to schedule to start via Task Scheduler. Or just run it when you log on (though you never log on to the console of a server do you…?).

It demonstrates how easy it is to get values out of the performance counters without having to resort to WMI.

    if((Get-Counter -Counter "\Processor(_Total)\% Processor Time").CounterSamples.CookedValue -ge 90){
        Send-MailMessage -Body "CPU is high, maybe take a look" -From "yourserver@yourdomain.com" -SmtpServer "smtp.yourdomain.com" -Subject "CPU High on yourserver" -To "you@yourdomain.com"
    Start-Sleep -Seconds 5

Clearly you could make this nicer, e.g. have a counter that stops it emailing more than once every x number of times within a certain time period.

This entry was posted in Performance, PowerShell and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.