Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting in-memory size of an object in Powershell

I've got a (long-running) script that I'm trying execute. Unfortunately, as it runs, the memory usage of powershell begins to creep up. The script is relatively simple, and I can't see any obvious memory leaks. However, I am using an API which may be poorly behaved.

Is there an easy way to get the in-memory size of an object from within powershell, so I can see if my suspicions are correct?

like image 296
dckrooney Avatar asked May 30 '12 22:05

dckrooney


People also ask

How do I check memory usage in PowerShell?

In Windows PowerShell there is no exclusive cmdlet to find out the CPU and memory utilization rates. You can use the get-wmi object cmdlet along with required parameters to fetch the results.

How do I find the length of an object in PowerShell?

You can use Measure-Object to count objects or count objects with a specified Property. You can also use Measure-Object to calculate the Minimum, Maximum, Sum, StandardDeviation and Average of numeric values. For String objects, you can also use Measure-Object to count the number of lines, words, and characters.

What does :: mean in PowerShell?

Static member operator :: To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. The member name may be an expression. PowerShell Copy.


2 Answers

Perhaps a crude way to do would be something like this:

$memBefore = (Get-Process -id $pid).WS
# Create object here...
$memAfter = (Get-Process -id $pid).WS
($memAfter - $memBefore) / 1KB

If it is a memory leak you might be able to mitigate it with:

[gc]::Collect()
like image 100
Andy Arismendi Avatar answered Oct 12 '22 05:10

Andy Arismendi


Another approx way:

$before = [gc]::GetTotalMemory($true)
$s = "A new string object"
$after = [gc]::GetTotalMemory($true)

($after - $before)/1kb # return the delta in KBytes
like image 27
CB. Avatar answered Oct 12 '22 05:10

CB.