问题
I want to get specific counters for processes that I have process id's for. However I can't think of a way to use where-object to match the process for the counter. Like
Where Gc '\process(*)\id process -eq 456 gc '\process($name)\working set'
So use the process id to retrieve the name and get the working set (or something to that effect).
回答1:
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"
回答2:
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
回答3:
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
回答4:
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"
来源:https://stackoverflow.com/questions/11067565/powershell-get-a-specific-process-counter-with-id-process