Aug 06

True windows process cpu utilization percentage using powershell

Recently I had to write a powershell script that grabbed the CPU percentage of a process running on one of our servers so we could trend it.  I figured this would be super simple task.  To my surprise this was quiet a challenge.  I tried several different approaches including get-process and get-wmiobject.  Most of the usual commands will return some value that’s either a process time, or a cpu percentage that’s not accurate unless you have a single core box.  After a little digging I figured it out, and since no one else out there has any really good example code I’m going to share with you my code:

 

#Define the process name
$ProcessName = "msiexec"
#Get the number of CPU cores
foreach ($proc in (Get-WmiObject  Win32_Processor)){if ($proc.numberofcores -eq $null){$cores++}else{$cores = $cores + $proc.numberofcores}}
#Get the process's perfmon counter for %Processor Time, divide by number of cores, and round to two decimal places 
[Math]::round(((((Get-Counter "\Process($ProcessName)\% Processor Time").Countersamples)[0].CookedValue)/$cores),2)

 

3 comments

    • Christopher Loyd on January 31, 2013 at 10:44 pm
    • Reply

    You are amazing. I’ve been searching for this for the past day or so, having tried to find something myself, but just as you it always gave inaccurate readings. Thank you for this! I have no idea why this was so hard.

    • Ryan on September 11, 2014 at 7:55 am
    • Reply

    This seems like exactly what I need, but for some reason it always returns zero? I’m 100% new to powershell, but if you have even the slightest insight I’d love to hear it.

    Thanks!

    • dubbul on April 4, 2016 at 5:02 pm
    • Reply

    I’m new to powershell and graphite. Can you provide me with powershell scripts(examples) and instructions how to to do from windows machine to graphite.

Leave a Reply

Your email address will not be published.