2
$i = 0;
while($i -lt 100) 
{
    $s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri '__echange__uri__' -Authentication Kerberos

    Import-PSSession $s

    Get-Module | where { $_.Name -match "tmp" } | Remove-Module
    Get-PSSession | Remove-PSSession

    $i = $i + 1
}

After executing the foregoing script, powershell runtime takes more than 3.5 GB of memory and I am unable to free this memory otherwise than by killing the whole process. I am suspecting that it has something to do with Import-PSSession command, probably a memory leak occurs. Is there a way to free memory alocated by Import-PSSession/New-PSSession without killing the powershell.exe process?

I use Powershell v3.0.

moody19871987
  • 81
  • 1
  • 10

1 Answers1

0

Invoking .NET Garbage Collector should help. Add [System.GC]::Collect() at the end of while loop just before the closing brace. You can also try Remove-Variable $s but it made no difference in my envrionment.

A similar question: How to instruct PowerShell to garbage collect .NET objects like XmlSchemaSet?

Community
  • 1
  • 1
Raf
  • 9,681
  • 1
  • 29
  • 41
  • Unfortunately your solution does not work for me. Neither GC.Collect() nor Remove-Variable doesn't prevent memory leaks. Did you test your solution? What Powershell version did you test on? I'm using PS v3.0. – moody19871987 May 21 '14 at 11:24
  • I tested it on on PS4 and the Garbage Collector did not prevent the leak entirely but it certainly slowed the growth rate by a huge factor. – Raf May 21 '14 at 11:27