简体   繁体   中英

CPU usage in percentage in Powershell

I want the CPU to be displayed as a percentage at the end of the code I wrote. 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

Thanks @Santiago for pointing out the issue that it was the reading for the same svchost instance everytime, this is fixed now.
The code below borrows heavily from this thread: Powershell Get a specific process counter with id process to get the correct reading.

This gets you the Path, the Id and %.

$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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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