简体   繁体   English

Powershell 中的 CPU 使用百分比

[英]CPU usage in percentage in Powershell

I want the CPU to be displayed as a percentage at the end of the code I wrote.我希望 CPU 在我编写的代码末尾显示为百分比。 Is there a way?有办法吗?

this is my code这是我的代码

Get-Process -name svchost |  % { $_.Path + " " + $_.Id + " " + $_.CPU}

I've barely made it this far, only the last part to go我几乎没有做到这一点,只有 go 的最后一部分

Thanks @Santiago for pointing out the issue that it was the reading for the same svchost instance everytime, this is fixed now.感谢@Santiago 指出每次都是读取同一个 svchost 实例的问题,现在已修复。
The code below borrows heavily from this thread: Powershell Get a specific process counter with id process to get the correct reading.下面的代码大量借鉴了这个线程: Powershell 获取具有 id process 的特定进程计数器以获得正确的读数。

This gets you the Path, the Id and %.这将为您提供路径、Id 和 %。

$procResult = Get-Process -Name svchost
$resultObjects = @();
foreach ($result in $procResult) {    
    $p = $((Get-Counter '\Process(*)\ID Process' -ErrorAction SilentlyContinue).CounterSamples | % { [regex]$a = "^.*\($([regex]::Escape($_.InstanceName))(.*)\).*$";[PSCustomObject]@{InstanceName=$_.InstanceName;PID=$_.CookedValue;InstanceId=$a.Matches($($_.Path)).groups[1].value}})
    $target = $p | where { $_.PID -eq $result.Id }
    $counterResult = Get-Counter -Counter "\Process($($target.InstanceName+$target.InstanceId))\% Processor Time" -ErrorAction SilentlyContinue
    if ($null -eq $counterResult) {
        continue;
    }
    $resultObjects += [PSCustomObject]@{
        Path = $result.Path
        Id = $result.Id
        CPU = $counterResult.CounterSamples[0].CookedValue
    }
}
$resultObjects | ft

You won't get the CPU usage in % with your code above.您不会通过上面的代码获得 % 的 CPU 使用率。 I really do not know why you insist on not changing the structure of your code as the structure of code is irrelevant as long as it is readable and get the job done.我真的不知道你为什么坚持不改变代码的结构,因为代码的结构是无关紧要的,只要它是可读的并且能完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM