Skip to content

Instantly share code, notes, and snippets.

@emnavarro02
Last active February 4, 2020 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emnavarro02/1495ab0dcbbfc33f1b5813332a1edd98 to your computer and use it in GitHub Desktop.
Save emnavarro02/1495ab0dcbbfc33f1b5813332a1edd98 to your computer and use it in GitHub Desktop.
Get top processes CPU consumers
#######################################################################################################################
# Get Top process CPU Consumers
# Author: Emerson Navarro
# Version: 0.1
#######################################################################################################################
# CHANGE LOG:
# - 29/01/2020:
# - Initial
# - 31/01/2019:
# - Changing CPU information from Win32_Process to \Process(*)\%Processor Time
# - Added CommandLine collumn
# - performance improvements
# - 04/02/2019:
# - Added PID Collumn
#######################################################################################################################
Param(
[Parameter(Mandatory=$false)]
[int] $TOP=10,
[Parameter(Mandatory=$false)]
[Bool] $FullName=$false # The amount of returned process. Default is 10.
)
Get-Counter "\Process(*)\% Processor Time" -ErrorAction SilentlyContinue `
| Select-Object -ExpandProperty CounterSamples `
| Where-Object {$_.Status -eq 0 -and $_.instancename -notin "_total", "idle"} `
| Sort-Object CookedValue -Descending `
| Select-Object TimeStamp,
# PID
@{
N="PID";E=
{
$procId = 0
try
{
$regex = [regex]"\((.*)\)"
$procName = [regex]::match($_.Path, $regex).Groups[1]
$procId = $(Get-WMIObject -query "SELECT IDProcess from Win32_PerfFormattedData_PerfProc_Process where Name like '$procName'").IDProcess
}
catch
{
# Do nothing
}
$procId
}
},
#Process Name
@{
N="Name";E=
{
$friendlyName = $_.InstanceName
try {
if (!$FullName) {
$regex = [regex]"\((.*)\)"
$friendlyName = [regex]::match($_.Path, $regex).Groups[1]
}
else{
$procId = [System.Diagnostics.Process]::GetProcessesByName($_.InstanceName)[0].Id
$proc = Get-WmiObject -Query "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId=$procId"
$procPath = ($proc | Where-Object { $_.ExecutablePath } | Select-Object -First 1).ExecutablePath
$friendlyName = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($procPath).FileDescription
}
}
catch
{
# Do nothing
}
$friendlyName
}
},
# CPU Utilization
@{
N="CPU";E=
{
($_.CookedValue/100/$env:NUMBER_OF_PROCESSORS).ToString("P")
}
},
# Command Line
@{
N="Command";E=
{
$cmdline = ""
try
{
$procId = [System.Diagnostics.Process]::GetProcessesByName($_.InstanceName)[0].Id
$cmdline = $(Get-WmiObject -Query "SELECT CommandLine from Win32_Process WHERE ProcessId=$procId").CommandLine
}
catch
{
# Do nothing
}
$cmdline
}
} -First $TOP | Format-Table -a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment