≡ Menu

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”
}

Comments on this entry are closed.

  • satish.Y March 29, 2012, 11:16 am

    Hi,

    I am looking for a tool from which i can collect the CPU utilization logs daily
    from windows 2008 server & 2003.

    Please help me in this

    Regards,
    Satish.Y

    • Sitaram Pamarthi March 29, 2012, 11:31 pm

      Satish, why can’t you use PerfMon logs to do the job?

  • siva May 31, 2012, 2:38 am

    Hi, we are running a application in OC4J server. When i monitor using
    Jconsole, i can see the graph the cpu usage is staying always more than 50%.
    Some time it reach more more than 100% and get server error.

    i want to monitor or find out what is keeping the CPU over 50% all that time.

    is there any tool i can use to connect to remote server and monitor what process are hogging up the CPU.

    thank you!
    Siva

  • Bill Jacobi August 20, 2012, 10:10 pm

    Hi, Similar to Siva, I am trying to throttle the cpu utilization of a hot process. I do this in Linux with cpulimit, http://cpulimit.sourceforge.net. How can I do this in PowerShell? Thx, Bill

    • Sitaram Pamarthi August 20, 2012, 11:39 pm

      Siva’s question is different. He want to know which process is taking high CPU on remote computer. I think this can be achieved by http://social.technet.microsoft.com/Forums/lv/winserverpowershell/thread/8d7502d4-9e67-43f7-94da-01755b719cf8. I haven’t tried it myself but let me how it goes.

      Bill, you question is about limiting the CPU utilization of a process. I haven’t came across such tool so far in windows. I will try do some research and let you know if I come across any. The requirement is interesting.

      • tim November 20, 2014, 11:33 am

        $i = 1
        $folder = Read-Host “What would you like to call the folder that you would like to save the Top Proccesses in?”
        $docname = Read-Host “What would you like to name the text file?”

        if ( -Not (Test-Path “c:\$folder”))
        {
        New-Item -Path “c:\$Folder” -ItemType directory | out-null
        }

        if ( -Not (Test-Path “c:\$folder\$docname”))
        {
        New-Item -Path “c:\$Folder\$docname.txt” -ItemType file -Force | out-null
        }

        $CPUPercent = @{
        Name = ‘CPUPercent’
        Expression = {
        $TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
        [Math]::Round( ($_.CPU * 100 / $TotalSec), 2)
        }
        }

        do{

        Get-Process |
        Select-Object -Property Name, CPU, $CPUPercent, Description |
        Sort-Object -Property CPUPercent -Descending |
        where-object {$_.CPUPercent -gt 5} |
        out-file -filepath c:\$Folder\$docname.txt -encoding ASCII -width 70 -Append

        $i++
        Start-Sleep -s 1

        } while ($i -lt 6)

        cls

        [System.Media.SystemSounds]::Beep.Play()
        Write-Host
        Write-Host
        Write-Host
        Write-Host
        Write-Host
        Write-Host
        Write-Host
        Write-Host
        Write-Host ———————————————————————— -foregroundcolor “cyan”
        Write-Host “Now wasn’t that fun.. Let’s See Whats in the file. :)” -foregroundcolor “cyan”
        write-host ———————————————————————— -foregroundcolor “cyan”

        pause

        Invoke-Item c:\$folder\$docname.txt

  • vinay September 10, 2012, 5:40 am

    it’s helpful for prod environment.

    But is it possible to get process name as well which is causing high CPU utilization.

  • Vishal December 4, 2012, 10:53 pm

    How do i run this script ?

    • Sitaram Pamarthi December 6, 2012, 12:32 pm

      Copy & Paste the code into Powershell console. Is it not helping?

  • Louis-Michel April 11, 2013, 2:28 am

    Hi, I try your script and I kept getting CPU utilization is below threshold level when I put cpu_threshold = 0…

    Thanks

  • james cherrill December 19, 2013, 4:30 pm

    I have been testing this script and it gives me the data I need however I need the script to repeat till the cpu threshold is reached but can’t seem to figure out how to do it.
    Any ideas?

    • Sitaram Pamarthi December 29, 2013, 4:24 pm

      James, you can do it by altering $repeat_count variable. For example, if you want to run it for long time, say 10 hours. Then do 600/5 and result, 120, should be the value of $repeat_count variable.

  • kalyan March 13, 2015, 6:24 pm

    Hi,

    I’m looking for a script which will monitor the CPU Usage,Memory Utilization of windows server.
    Condition:- Email should be triggered at any point to end users when CPU and Memory usage crosses 75%.

  • Lucky August 9, 2016, 10:38 pm

    I too am looking for such a script which Kalyan have requested, can someone help…

  • jack May 24, 2017, 6:59 pm

    Works like a charm for me on a windows2008R2 server !

    for newbies:

    run this command first (one time):
    Set-ExecutionPolicy RemoteSigned

    to start the script:
    PowerShell -NoExit “C:\scripts\script.ps1”

  • Asghar October 25, 2021, 2:59 pm

    Hi sir ,
    I wanted to ask about the send mail cmdlet , to how to setup in order to get notifed at gmail..pls explain how to configure