galahad
galahad

Reputation: 209

Get CPU % of a particular process using powershell

I want to get the CPU usage % (not processor time) of a particular process using a powershell command.

Example: (Windows 8 Task Manager) enter image description here

I want to get that 2.9% with a command.

Upvotes: 0

Views: 27276

Answers (3)

Babu Dhinakaran
Babu Dhinakaran

Reputation: 11

PowerShell will return the number of seconds that the process was running in the CPU easily with Get-Process -Name system | select CPU. You can get the cpu time at 2 instance and then calculate the percent of CPU usage as (cpu2-cpu1)/(t2-t1)*100. 100 means the process was using 100% of a CPU core. Divide this number by the number of cores to have the percent of CPU usage in the same scale as Task Scheduler is using.

$processName = 'OUTLOOK'
$sleep_time = 1 # value in seconds
while (1) {
  $CPU_t1 = Get-Process -Name $processName | Select CPU
  $CPU_t1_sec = $($CPU_t1.CPU)
  #Write-Host "CPU_t1: $($CPU_t1.CPU)"
  $date1 = (Get-Date)
  sleep -Seconds $sleep_time
  $CPU_t2=Get-Process -Name $processName | Select CPU
  #Write-Host "CPU_t2: $($CPU_t2.CPU)"
  $CPU_t2_sec = $($CPU_t2.CPU)
  $date2 = (Get-Date)
  $date_diff = $date2 - $date1
  $diff_time = $date_diff.seconds
  #Write-Host "TimeDiff: $diff_time"
  #compute them to get the percentage
  $CPU_Utilization = ($CPU_t2_sec - $CPU_t1_sec)/$diff_time 
  $CPU_Utilization_per = $CPU_Utilization * 100
  #Sleep $sleep_time
  Clear-Host 
  Write-Host "CPU_Utilization_Per: $CPU_Utilization_per" 
  #Write-Host "====================="
}

Upvotes: 0

Rail
Rail

Reputation: 700

Here is the correct answer which is support case then you have multiple processs with same name https://stackoverflow.com/a/34844682/483997

# To get the PID of the process (this will give you the first occurrance if multiple matches)
$proc_pid = (get-process "slack").Id[0]

# To match the CPU usage to for example Process Explorer you need to divide by the number of cores
$cpu_cores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors

# This is to find the exact counter path, as you might have multiple processes with the same name
$proc_path = ((Get-Counter "\Process(*)\ID Process").CounterSamples | ? {$_.RawValue -eq $proc_pid}).Path

# We now get the CPU percentage
$prod_percentage_cpu = [Math]::Round(((Get-Counter ($proc_path -replace "\\id process$","\% Processor Time")).CounterSamples.CookedValue) / $cpu_cores)

Upvotes: 1

Michael Noe
Michael Noe

Reputation: 82

Get-Process -Name PowerShell | Select CPU

Is this what you're looking for? Or something more monitoring based?

param
(
   [String]
   [Parameter(Mandatory)]
   $Title
)

do
{
   $process = Get-Process -Name $Title
   $process
   Start-Sleep -Seconds 1
} while ($process)

Upvotes: -3

Related Questions