title: Dispose of SearchResultCollection after foreach-object
body: <p>According <a href="https://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.findall.aspx#Anchor_2" rel="nofollow noreferrer">MSDN</a> remarks, <code>.Dispose()</code> must be called on a <code>System.DirectoryServices.SearchResultCollection</code> after you are done with it.</p>
  
  <blockquote>
    <p>Due to implementation restrictions, the SearchResultCollection class cannot release all of its unmanaged resources when it is garbage collected. <strong>To prevent a memory leak, you must call the Dispose method when the SearchResultCollection object is no longer needed</strong>.</p>
  </blockquote>
  
  <p>I am also reading that you should use <code>Foreach-Object</code> instead of <code>foreach</code> to save memory because <code>foreach</code> requires the entire <code>SearchResultCollection</code> to be saved to memory before it can be iterated on.</p>
  
  <pre><code>$objSearcher.FindAll() | Foreach-Object { $_ }
  </code></pre>
  
  <p>is better than</p>
  
  <pre><code>$objResults = $objSearcher.FindAll()
  foreach($objResult in $objResults)
  {
      $objResult
  }
  </code></pre>
  
  <p>What I cannot figure out is how to call <code>.Dispose()</code> if you use <code>Foreach-Object</code>?</p>