PoshCode Logo PowerShell Code Repository

Memory helper functions (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/973"></script>download | new post

Memory management helpers. Set-SessionVariableList creates a baseline of variable names. Remove-NewVariable clears out any variables not in the SessionVariableList and calls the garbage collector to free up memory.

  1. Function Add-SessionVariable()
  2. {
  3.         param ([string[]]$VariableName=$null)
  4.        
  5.         [string[]]$VariableNames = [AppDomain]::CurrentDomain.GetData('Variable')
  6.         $VariableNames += $VariableName
  7.        
  8.         if ($input)
  9.         {
  10.                 $VariableNames += $input
  11.         }
  12.        
  13.         #To Not Waste Space, Remove Duplicates
  14.         $VariableNames = $VariableNames | Select-Object -Unique
  15.        
  16.         [AppDomain]::CurrentDomain.SetData('Variable',$VariableNames)
  17. }
  18.  
  19. Function Set-SessionVariableList()
  20. {
  21.         $VariableNames = Get-Variable -scope global| ForEach-Object {$_.Name}
  22.         Add-SessionVariable $VariableNames
  23.        
  24.         Write-Verbose 'Loaded Variable Names into AppDomain'
  25.         $counter = 1
  26.         Foreach ($Variable in $VariableNames)
  27.         {
  28.                 Write-Verbose "`t $($counter): $Variable"
  29.                 $counter++
  30.         }
  31. }
  32.  
  33. Function Get-SessionVariableList()
  34. {
  35.         [AppDomain]::CurrentDomain.GetData('Variable')
  36. }
  37.  
  38. Function Remove-NewVariable()
  39. {
  40.         $StartingMemory = (Get-Process -ID $PID).WS / 1MB
  41.         Write-Verbose "Current Memory Usage: $StartingMemory MB"
  42.  
  43.         $VariableNames = Get-SessionVariableList
  44.         $VariableNames += 'StartingMemory'
  45.         Get-Variable -scope global | Where-Object {$VariableNames -notcontains $_.name} | Remove-Variable -scope global
  46.        
  47.         [GC]::Collect()
  48.        
  49.         $EndingMemory = (Get-Process -ID $PID).WS / 1MB
  50.         Write-Verbose "Ending Memory: $EndingMemory MB"
  51.        
  52.         $Diff = $StartingMemory - $EndingMemory
  53.         Write-Verbose "Freed up: $Diff MB"
  54. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me