The Usual Tech Ramblings

PowerShell: Top x Processes using CPU

This is a quick and handy one for server monitoring, and tracking down that process that is using all your CPU. It makes use of WMI counters.

Get-WmiObject Win32_PerfFormattedData_PerfProc_Process | `
  where-object{ $_.Name -ne "_Total" -and $_.Name -ne "Idle"} | `
  Sort-Object PercentProcessorTime -Descending | `
  select -First 5 | `
  Format-Table Name,IDProcess,PercentProcessorTime -AutoSize

Okay, this one is a mouthful of pipes, and formatting to make it easier to see. But the breakdown is pretty easy…

  • Get the process information
  • Exclude _Total and Idle1
  • Sort the output by descending processor usage
  • Only get the first 5 rows
  • Format the results into a table, with the columns Name, Process ID, and processor usage.

Output looks something like this:

Name       IDProcess PercentProcessorTime
----       --------- --------------------
chrome#2        3912                   24
System             4                   12
svchost#12      4276                    0
mobsync         5688                    0
wmpnetwk        3396                    0

Another handy hint here, the back-tick is PowerShell’s way of allowing you to line-wrap. This makes it a little easier to read, especially when giving it as samples like above.

I’ll be bundling parts of this for Nagios to return what processes are using the most processor when I get CPU alerts, allowing me to make quicker judgments on what I need to do to correct the issue.

  1. _Total is a counter value, and Idle is a value the system records, bring up task manager and you should see it as ‘System Idle Process’