Get CPU % of a particular process using powershell

穿精又带淫゛_ 提交于 2021-02-07 04:37:36

问题


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

Example: (Windows 8 Task Manager)

I want to get that 2.9% with a command.


回答1:


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)



回答2:


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)



回答3:


Get-Process -Name system | select CPU

Get the cpu time at 2 instance as (cpu2-cpu1)/(t2-t1)*100. You will get CPU value in %.

Get-Process -Name system | select CPU # Get the cpu time at 2 instance as (cpu2-cpu1)/(t2-t1)*100. You will get CPU value in %.

$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 "====================="
}


来源:https://stackoverflow.com/questions/39712631/get-cpu-of-a-particular-process-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!