6

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?

1
  • What kind of API are you using ? Commented May 30, 2012 at 23:26

3 Answers 3

9

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Managed to hack something together... Turned out the API did have a memory leak, but I was able to get around it once I found the culprit. Thanks!
I think [gc]::Collect() is a godsend for when working with Powershell.. Andy, do you mind if I ask if was this a 3rd-party COM object, or something part of the Windows OS / .NET?
@indifferentDrum [gc] is a built-in type. I've had to use to solve this third-party library issue which deals with open files.
6

Another approx way:

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

($after - $before)/1kb # return the delta in KBytes

Comments

0

This looks right, from reddit. At least for simple types.

using namespace System.Runtime.InteropServices
$tmp = 1234567890 # int32
[Marshal]::SizeOf($tmp)

4


$tmp = 12345678900 # int64
[Marshal]::SizeOf($tmp)

8


$tmp = 12345678900000000000 # decimal
[Marshal]::SizeOf($tmp)

16


[Marshal]::SizeOf

OverloadDefinitions
-------------------
static int SizeOf(System.Object structure)
static int SizeOf(type t)
static int SizeOf[T](T structure)
static int SizeOf[T]()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.