Dispose of SearchResultCollection after foreach-object

Viewed 386

According MSDN remarks, .Dispose() must be called on a System.DirectoryServices.SearchResultCollection after you are done with it.

Due to implementation restrictions, the SearchResultCollection class cannot release all of its unmanaged resources when it is garbage collected. To prevent a memory leak, you must call the Dispose method when the SearchResultCollection object is no longer needed.

I am also reading that you should use Foreach-Object instead of foreach to save memory because foreach requires the entire SearchResultCollection to be saved to memory before it can be iterated on.

$objSearcher.FindAll() | Foreach-Object { $_ }

is better than

$objResults = $objSearcher.FindAll()
foreach($objResult in $objResults)
{
    $objResult
}

What I cannot figure out is how to call .Dispose() if you use Foreach-Object?

2 Answers
Related