Dispose of SearchResultCollection after foreach-object Dispose of SearchResultCollection after foreach-object powershell powershell

Dispose of SearchResultCollection after foreach-object


The foreach language statement is not equivalent to the ForEach-Object cmdlet, although they have similar purposes. (Unfortunately, ForEach-Object has a default alias of foreach, which IMO only adds to the confusion.)

My recommendation is not to use ForEach-Object when iterating directory search results, as DirectorySearcher is efficient and doesn't need ForEach-Object. (I also recommend Write-Progress as a part of your iteration, as DirectorySearcher might return a long list.)

ForEach-Object is useful when you want PowerShell's streaming behavior and you might not have an efficient search.


Bill Stewart is right. .FindAll() returns an IEnumerable so it doesn't matter which one you choose.

But to your question of how to Dispose of the object with ForEach-Object, because of the above, you can store it in a variable first just like you did with foreach, then pipe that:

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