Skip to main content

Powershell not returning same memory use as Task Manager

Task Manager gets that information from a performance counter, which is not directly available from the information returned by Get-Process.  You can get to the information with PowerShell, though.  This example uses the Get-Counter cmdlet, which is new to PowerShell 4.0 (though you can use the underlying .NET classes to accomplish something similar in older versions of PowerShell, if needed.)

Get-Process | 
ForEach-Object { 
$proc = $_ 
$counter = Get-Counter -Counter "\Process($($proc.Name))\Working Set - Private" 

$pws = 'Unknown' 
if ($null -ne $counter) 

  $pws = $counter.CounterSamples[0].CookedValue 


$proc | Add-Member -NotePropertyName 'PrivateWorkingSetSize' -NotePropertyValue $pws -PassThru 
} | Format-Table ProcessName,Id,PrivateWorkingSetSize


This method is not fast.

From: https://social.technet.microsoft.com/Forums/windowsserver/en-US/46665ab7-0a22-41b5-968c-b3942e9b4a4c/getprocess-differs-from-task-manager-in-memory-usage?forum=winserverpowershell

In the end, I preferred this version that worked on Server 2008 to highlight the top 5 processes by memory usage and also account for total memory usage.


$totalmem = 0 

$topslots = 5 
$x = 0 

$topMemProcesses = ""

Get-Process | Sort-Object WS -Descending | 
ForEach-Object {
    $proc = $_

    $counter = Get-Counter -Counter "\Process($($proc.Name))\Working Set - Private" -ErrorAction SilentlyContinue

    $pws = 0
    $alert = ''
    if ($null -ne $counter)
    {
        $pws = $counter.CounterSamples[0].CookedValue
    } else { 
        $alert = 'Unknown or Already Terminated'    
    }

    # Add-Member -InputObject $proc -Name 'PrivateWorkingSetSize' -Value $pws -PassThru
    
    $ProcessName = $proc.Name
    $ProcessId = $proc.Id
    
    
    $totalmem = $totalmem + $pws

    if ( $x -lt $topslots ) { 
        $pwsMB = [int]($pws/1024/102.4)
        $pwsMB = $pwsMB / 10
        $topMemProcesses = $topMemProcesses + "$ProcessName,$ProcessId,$pwsMB,$alert`r`n"
        $x++ 
    }
} 

write-host  $topMemProcesses 
write-host  ( $totalmem / 1024 / 1024 / 1024 ) 
#|
# Format-Table ProcessName,Id,PrivateWorkingSetSize

Comments

Popular posts from this blog

Javascript Form Validation

It's real simple. All you need to do is call a javascript function in a html  " onsubmit " in the form tag as a javascript return, like this       <form method="post" action="dosomething.php" onsubmit="return validateForm();"> If the code completes ok, the form is then sent to the page listed in "action" http://www.w3schools.com/js/js_form_validation.asp If the function specified in the onsubmit returns false, then the form is not sent to the page mentioned in action.