Object Disposal in Power Shell scripting for SharePoint 2010


In this article I am trying to explain object disposal in Power Shell. Most of us are aware of object disposal in SharePoint object model. In scenarios in which we use SharePoint objects extensively-for example, in SharePoint sites that use custom Web Parts or event handler etc.it can cause the following unusual behaviors if we are not disposing of SharePoint objects once we finished with the operation. The following are the main causes if you don't dispose SharePoint objects properly in custom coding.

  • Frequent recycles of the Windows SharePoint Services application pool, especially during peak usage

  • Application crashes that appear as heap corruption in the debugger

  • High memory use for Microsoft Internet Information Services (IIS) worker processes

  • Poor system and application performance

Similarly in Power shell scripting also we have to adopt disposal practices to avoid memory leakage resulting in performance issues on your servers.

We have two methods for disposal practice

  1. Explicitly dispose every object you create

  2. Use SpAssignmentGlo

Explicitly dispose every object you create

Please find one example for explicit dispose

$template = Get-SPWebTemplate "STS#0"
New-SPSite -Url "your Site collection URL" -OwnerAlias "domain\user" -Template $template
$template.dispose()

SpAssignment

Any objects defined between the Start-SPAssignment –Global and Stop-SPAssignment –Global commands will be automatically disposed of by PowerShell.You don't have to explicitly dispose each object you created

Start-SPAssignment –Global

$template = Get-SPWebTemplate "STS#0"
New-SPSite -Url "your Site collection URL" -OwnerAlias "domain\user" -Template $template

Stop-SPAssignment –Global

Up Next
    Ebook Download
    View all
    Learn
    View all