Question

This script snippet is accessing a SharePoint site (web) within a function. It creates a SPWeb object that should get disposed of by the end of the function to avoid a memory leak. Usually the way to dispose of an object is something like $web.dispose(). In this case the SPWeb object is created and used in a pipeline but doesn't have a name.

Here is the code:

function foobar {
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" |
         ForEach-Object {$_.Lists | Where {$_.Title -EQ "someLibrary"} |  
         Select ID }
}

I suspect that the SPWeb object is not automatically disposed of at the end of the pipeline and is causing a memory leak.

How do I dispose of objects created in a pipeline? Do I even need to?

FYI: $x does not have a method named 'Dispose', so $x.Dispose() does not work.

Was it helpful?

Solution

I don't know about "auto" disposing of the objects but to have the Dispose method available, you need to break the command. As it is right now, the end result is a list object which doesn't support that method.:

function foobar {
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2"
    $list = $x.Lists['someLibrary'].Id
    $x.Dispose()
    $list
}

OTHER TIPS

More in keeping with PowerShell vernacular is to maintain the pipeline by using Start-SPAssignment and Stop-SPAssignment, eg

function foobar {
    $assig = Start-SPAssignment
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" -AssignmentCollection $assign |
         ForEach-Object {$_.Lists | Where {$_.Title -EQ "someLibrary"} |  
         Select ID }
    Stop-SPAssignment $assign
}

This is only an illustration not a verified code sample as I don't have a SharePoint server handy at the moment to test it, but it gives you the idea. If I get a chance I'll test it and edit my answer accordingly.

A further refinement is to collapse the ForEach into the pipeline

function foobar {
    $assig = Start-SPAssignment
    $x = Get-SPWeb -Identity "http://mylocalsite/Sites/test1/test2" -AssignmentCollection $assign |
         Select-Object -ExpandProperty Lists | 
         Where {$_.Title -EQ "someLibrary"} |  
         Select ID
    Stop-SPAssignment $assign
}

Once again only an illustration not a verified code sample.

The following blog post gives a good tutorial on the assignment object, PowerShell, SharePoint and Memory Leaks (Start-SPAssignment).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top