PowerShell Memory Leak and Prevention

Memory Leak

When writing PowerShell scripts, there are immense chances to form memory leaks if the script-writer did not free the objects correctly. When dealing with SPFarm, SPSiteAdministration SPSite and SPWeb objects with huge internal data, the problem can become more vulnerable when crunching system resources.

Preventions

We can prevent memory leaks quickly using the following Cmdlets:

  • Start-SPAssignment
  • Stop-SPAssignment

Start- SPAssignment & Stop-SPAssignment

Start-SPAssignment will start collecting memory objects. Later we can invoke the Stop-SPAssignment to release the memory.

  1. $c = Start-SPAssignment;  
  2.   
  3. $w = Get-SPWeb –Site http://serfver –AssignmentCollection $c  
  4.   
  5. Stop-SPAssignment $c;  

Explanation

In the preceding code, we are first declaring the variable $c pointing to collect the assignment objects. In the next line Get-SPWeb will create a web object in $w and simultaneously it is added to the assignment collection. The Stop-SPAssignment will release all the memory-objects within $c.

Here additional coding is required to add the web objects to the assignment collection. In production scenarios a pre-existing PowerShell script must be modified and that will require much effort.

Using –Global Switch

We can do memory leak prevention quickly using the –Global switch. An example is given below:

  1. Start-SPAssignment -Global  
  2.   
  3. $w = Get-SPWeb –Site http://serfver –AssignmentCollection $c  
  4.   
  5. Stop-SPAssignment -Global  
Types of Assignment

There are the following 3 types of assignments: 
  • No Assignment
  • Simple Assignment
  • Advanced Assignment
Simple Assignment is the one we have seen using the –Global parameter. This is used more often.

Advanced Assignment is the one with an assignment variable. This is used in advanced scripts.

No Assignment is where no parameters or variables are used. Here objects are disposed of in each iteration.

References

https://technet.microsoft.com/en-us/library/ff607664.aspx

Summary

In this article we explored how to prevent memory leaks when writing SharePoint scripts.

Up Next
    Ebook Download
    View all
    Learn
    View all