Search code examples
sharepointpowershellscopepiping

Proper disposal of powershell pipeline objects


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.


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
    }