CPU and memory usage in percentage for all processes in Powershell

天大地大妈咪最大 提交于 2020-06-10 05:18:50

问题


Is there a way for viewing CPU and memory utilization in percentage for all running processes in PowerShell?

I have tried the following:

Get-Process | %{"Process={0} CPU_Usage={1} Memory_Usage={2}" -f $_.ProcessName,[math]::Round($_.CPU),[math]::Round($_.PM/1MB)}

Along with it I have parsed this information and calculated memory usage percentage from total memory, but couldn't get the same for CPU since by this command it show CPU time division in processes not utilization per se.

Used the following commands for total memory and total cpu utilization:

  1. TOTAL PHYSICAL MEMORY

    Get-WmiObject Win32_OperatingSystem | %{"{0}" -f $_.totalvisiblememorysize}

  2. TOTAL CPU UTILIZATION

    Get-WmiObject Win32_Processor | Select-Object -expand LoadPercentage

Any help would be appreciated. I need it in the following format:

PROCESS=process_name CPU=percent_cpu_utilization_by_process MEMORY=percent_memory_utilization_by_process

回答1:


You can use the WMI object Win32_PerfFormattedData_PerfProc_Process to collect all this data.

Get-WmiObject Win32_PerfFormattedData_PerfProc_Process `
    | Where-Object { $_.name -inotmatch '_total|idle' } `
    | ForEach-Object { 
        "Process={0,-25} CPU_Usage={1,-12} Memory_Usage_(MB)={2,-16}" -f `
            $_.Name,$_.PercentProcessorTime,([math]::Round($_.WorkingSetPrivate/1Mb,2))
    }

If you need the memory in a percentage of total memory you can add the following at the start to get the total RAM in the system.

$RAM= Get-WMIObject Win32_PhysicalMemory | Measure -Property capacity -Sum | %{$_.sum/1Mb} 

Then change the WorkingSetPrivate calculation to the following

([math]::Round(($_.WorkingSetPrivate/1Mb)/$RAM*100,2))

Note the CPU stat in this WMI object is rounded to the nearest present and I have calculated the current used memory in Megabytes. For more information on this class see this link.




回答2:


Did you try Get-Counter cmdlet?

The Get-Counter cmdlet allows you to get performance counter data for local/remote machines.

Have a look at the blog for more details:

http://www.adminarsenal.com/admin-arsenal-blog/powershell-get-cpu-usage-for-a-process-using-get-counter/



来源:https://stackoverflow.com/questions/39244580/cpu-and-memory-usage-in-percentage-for-all-processes-in-powershell

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