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)
Comments
Author: Christopher Loyd
Date: 2013-01-31 22:44:20
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.
Author: Ryan
Date: 2014-09-11 07:55:55
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!
Author: dubbul
Date: 2016-04-04 17:02:33
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.
Author: etets
Date: 2018-07-24 09:40:20
It’s not even working.
Get-Counter : The \Process(msiexec)% Processor Time performance counter path is not valid.
At C:\logs\test.ps1:6 char:19
-
… ::round(((((Get-Counter “\Process($ProcessName)% Processor Time”).Co …
-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-
CategoryInfo : InvalidResult: (:) [Get-Counter], Exception
-
FullyQualifiedErrorId : CounterPathIsInvalid,Microsoft.PowerShell.Commands.GetCounterCommand
-
Cannot index into a null array.
At C:\logs\test.ps1:6 char:1
-
[Math]::round(((((Get-Counter “\Process($ProcessName)% Processor Tim …
-
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray