How to get Memory (Private working set) per users in powershell

I'm trying to get the memory usage of process per user (like task manager), that info comes to Memory (Private working set) if we convert that values into MB we should get the memory usage, like in the users view in task manager...

Maybe i missing something, if someone know about this pls tell me.

And this is my script

Get-WmiObject Win32_Process | Sort-Object -Property privatememorysize -Descending | 
Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.privatememorysize/ 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}} | fl *

Upvotes: 0

Views: 2715

Answers (2)

TheMadTechnician
TheMadTechnician

Reputation: 36322

The issue is that the Win32_Process class doesn't have a property named 'privatememorysize'. Replacing that with 'privatepagecount' instead makes this work as expected.

Get-WmiObject Win32_Process | Sort-Object -Property privatepagecount -Descending | 
    Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.privatepagecount/ 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}}

I see, that is not the same, so we have the issue here where the WMI object doesn't give private working set, and other methods that do include that don't have the user. So what we can do is use Get-Process to get each process and the private working set, and use Get-WMIObject to get the user associated with each object, and then match them up. Probably best to make a hashtable from one to reference, then use that to add the property to the other object. So, let's do that!

#Get WMI Process objects
$WMIProcs = Get-WmiObject Win32_Process
#Get Get-Process object
$GPProcs = Get-Process
#Convert Get-Process objects to a hashtable for easy lookup
$GPHT = @{}
$GPProcs | ForEach-Object {$GPHT.Add($_.ID.ToString(),$_)}
#Add PrivateWorkingSet and UserID to WMI objects
$WMIProcs|ForEach-Object{ 
    $_ | Add-Member "Mem Usage(MB)" $([math]::round($GPHT[$_.ProcessId.ToString()].PrivateMemorySize64/1mb,2))
    $_ | Add-Member "UserID" $($_.getowner().Domain+"\"+$_.getowner().user)
}
#Output to screen
$WMIProcs | Format-Table ProcessName, "Mem Usage(MB)", UserID

Upvotes: 1

Rich Moss
Rich Moss

Reputation: 2384

Try using WorkingSetSize instead of PrivateMemorySize.

Get-WmiObject Win32_Process | Sort-Object -Property WorkingSetSize -Descending | 
Select processname, @{Name="Mem Usage(MB)";Expression={[math]::round($_.WorkingSetSize / 1mb,2)}},@{Name="UserID";Expression={$_.getowner().Domain+"\"+$_.getowner().user}} | FL

Upvotes: 1

Related Questions