Powershell Get CPU Percentage

喜你入骨 提交于 2019-12-11 00:51:59

问题


There doesn't seem to be any simple explanations on how to get CPU Percentage for a process in Powershell. I've googled it and searched here and I'm not seeing anything definitive. Can somebody explain in layman terms how to get CPU Percentage for a process? Thanks!

Here's something to get you started ;)

$id4u = gps | ? {$_.id -eq 412}
function get_cpu_percentage {
# Do something cool here
}
get_cpu_percentage $id4u

回答1:


Using WMI:

get-wmiobject Win32_PerfFormattedData_PerfProc_Process | ? { $_.name -eq 'powershell' } | select name,  PercentProcessorTime

Function:

    function get_cpu_percentage ($id )
{
(get-wmiobject Win32_PerfFormattedData_PerfProc_Process | ? { $_.idprocess -eq $id.id }).PercentProcessorTime
}

$id4u = gps | ? {$_.id -eq 412}
get_cpu_percentage -id $id4u



回答2:


How about this?

gps powershell_ise | Select CPU

Mind you, this is a scriptProperty and won't show anything for remote systems. This is known.




回答3:


get-counter provides information on system performance. You can obtain information on single processes as well. There is more about it here: http://social.technet.microsoft.com/Forums/lv/winserverpowershell/thread/8d7502d4-9e67-43f7-94da-01755b719cf8 and here http://blogs.technet.com/b/heyscriptingguy/archive/2010/02/16/hey-scripting-guy-february-16-2010a.aspx I'm not sure if this is what you are looking for, but here is one possibility using the process name and get-counter.

Note: if you have more than 1 processor i believe you should divide the result by the number of processors. You can get this value using:

$env:NUMBER_OF_PROCESSORS



    function get_cpu_percentage {
    param([string[]]$myProc)
    return (get-counter -Counter "\Process($myProc)\% processor time" -SampleInterval 5 -MaxSamples 5 | select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average
    }
    get_cpu_percentage ("powershell")

or using proc id and gps:

Note: I believe the value returned by get-process is the CPU seconds used by the process since start up. It is not the cpu percentage used.

    function get_cpu_since_start{
    param ([system.object]$p)
    $id4ucpu = $p | select-object CPU
    return $id4ucpu.CPU
    }
get_cpu_since_start (gps | ? {$_.id -eq 412})


来源:https://stackoverflow.com/questions/11125950/powershell-get-cpu-percentage

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