Get Memory Consumption

by May 15, 2015

To get a rough understanding how much memory a script takes, or how much memory PowerShell puts aside when you store results in a variable, here is a helper function:

#requires -Version 2

$script:last_memory_usage_byte = 0

function Get-MemoryUsage
  $memusagebyte = [System.GC]::GetTotalMemory('forcefullcollection')
  $memusageMB = $memusagebyte / 1MB
  $diffbytes = $memusagebyte - $script:last_memory_usage_byte
  $difftext = ''
  $sign = ''
  if ( $script:last_memory_usage_byte -ne 0 )
    if ( $diffbytes -ge 0 )
      $sign = '+'
    $difftext = ", $sign$diffbytes"
  Write-Host -Object ('Memory usage: {0:n1} MB ({1:n0} Bytes{2})' -f  $memusageMB, $memusagebyte, $difftext)

  # save last value in script global variable
  $script:last_memory_usage_byte = $memusagebyte

You can run Get-MemoryUsage anytime, and it returns the current memory consumption as well as the delta to the last call.

Key is the use of the garbage collector: it is responsible for freeing memory but by default does not free memory immediately. To roughly calculate memory consumption, the garbage collector needs to be instructed to free all unused memory immediately, then report back the currently allocated memory.

Twitter This Tip! ReTweet this Tip!