CPU and memory usage in percentage for all process

2020-06-23 11:35发布

问题:

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/