Techibee.com

Get CPU utilization of a computer using powershell

Earlier I wrote a small code to get the CPU utilization of computer using powershell and performance counters. Recently a user posted a question to know the procedure to monitor CPU utilization and get a alert when CPU utilization exceeds a given threshold value.

So, I am writing this article to share the code for monitoring CPU utilization of a computer and report via email when it exceeds a given value.

At the beginning of the script there are a few variables which you need to adjust according to your requirement. They are self descriptive, so I feel no explanation is required. Also you should change the “From”, “To”, and “Server” parameters of “Send-MailMessage” cmdlet in script to receive email. Feel free to write to me if you have any questions.

Save the below code to a file and name it as “cpu-monitor.ps1” and run it on the computer you want. Script checks the CPU utilization for every 5 seconds for three times and reports if it finds CPU utilization is greater than given threshold value every time it measured.

$repeat_count = 3
$cpu_threshold = 85
$sleep_interval = 5
$hit = 0
foreach($turn in 1..$repeat_count) {
$cpu = (gwmi -class Win32_Processor).LoadPercentage
#write-host “CPU utilization is Currently at $cpu`%”
If($cpu -ge $cpu_threshold) {
$hit = $hit+1
}
start-sleep $sleep_interval
}

if($hit -eq 3) {
write-host “CPU utilization is over threshold”

Send-MailMessage –From cpumonitor@localdomain.com –To toaddress@yourdomain.com –Subject “CPU Utilization is more than $cpu_threshold`%” –Body “CPU Utilization is more than $cpu_threshold`%” –SmtpServer smtpserver.domain.com
} else {
write-host “CPU utilization is below threshold level”
}

Exit mobile version