Powershell Get a specific process counter with id process

白昼怎懂夜的黑 提交于 2019-12-04 08:51:34

You can get counters for a process name so first get the process name by using its Id and then embed the process name in the counter. For example:

$id = # your process id
$proc = (Get-Process -Id $id).Name
Get-Counter -Counter "\Process($proc)\% Processor Time"

It seems a bit convoluted to get the correct performance counter path for a process with multiple instances of the same process name:

$proc_id=6580
$proc_path=((Get-Counter "\Process(*)\ID Process").CounterSamples | ? {$_.RawValue -eq $proc_id}).Path
Get-Counter ($proc_path -replace "\\id process$","\% Processor Time")

Timestamp                 CounterSamples
---------                 --------------
11/20/2014 5:39:15 PM     \\myhost\process(conhost#2)\% processor time :
                          0

It's easy with the get-process commandlet. Just filter the output for the process id you want using where-object, then select the parameters you're interested in:

get-process | where-object{ $_.id -eq 456 } | select name,workingset

If you want a solution that also include process with multiple instance IDs you can use :

$p = $((Get-Counter '\processus(*)\id de processus' -ErrorAction SilentlyContinue).CounterSamples | % {[regex]$a = "^.*\($([regex]::Escape($_.InstanceName))(.*)\).*$";[PSCustomObject]@{InstanceName=$_.InstanceName;PID=$_.CookedValue;InstanceId=$a.Matches($($_.Path)).groups[1].value}})
$id = # your process id
$p1 = $p | where {$_.PID -eq $id}
Get-Counter -Counter "\Process($($p1.InstanceName+$p1.InstanceId))\% Processor Time"
# In french
# Get-Counter -Counter "\Processus($($p1.InstanceName+$p1.InstanceId))\% temps processeur"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!