title: PowerShell: Find and delete folders that have no files in them or in child folders
body: <p>I have a PowerShell 2.0 script that I use to delete folders that have no files in them:</p>
  <pre><code>dir 'P:\path\to\wherever' -recurse | Where-Object { $_.PSIsContainer } | Where-Object { $_.GetFiles().Count -eq 0 } | foreach-object { remove-item $_.fullname -recurse}
  </code></pre>
  <p>However, I noticed that there were a ton of errors when running the script. Namely:</p>
  <pre><code>Remove-Item : Directory P:\path\to\wherever cannot be removed because it is not empty.
  </code></pre>
  <p><em><strong>&quot;WHAT?!&quot;</strong></em> I panicked. They should <em><strong>all</strong></em> be empty! I filter for only empty folders! Apparently that's not quite how the script is working. In this scenario a folder that has only folders as children, but files as grandchildren is considered empty of files:</p>
  <pre><code>Folder1 (no files - 1 folder) \ Folder 2 (one file)
  </code></pre>
  <p>In that case, PowerShell sees Folder1 as being empty and tries to delete it. The reason this puzzles me is because if I right-click on Folder1 in Windows Explorer It says that Folder1 has 1 folder and 1 file within it. Whatever is used to calculate the child objects underneath Folder1 from within Explorer allows it to see grandchild objects ad infinitum.</p>
  <h1>Question:</h1>
  <p>How can I make my script not consider a folder empty if it has files as grandchildren or beyond?</p>