title: Remove all empty folders in a subfolder using a batchfile?
body: <p>I have a script that will delete all files older than 31 days from a nested file structure.</p>
  
  <p>At some point, it will leave empty folders in place, and I'm looking for a way to delete them, ideally keep folders that are newer than 31 days. Given that <code>rd FolderName</code> will not remove a folder if its not empty, I can use this to delete folders. The problem is, if I do this, it will not remove all empty folders, only the one that is deepest in the tree. If I could reverse the list forfiles gives me, it would work. If that's not possible, is there another way?</p>
  
  <p>NB: rd /s will not just remove folders nested, but will also remove its files. I don't want to remove the folder if its not empty.</p>
  
  <p>Here's my script:</p>
  
  <pre class="lang-bat prettyprint-override"><code>@echo off
  cd /d "C:\MyPath"
  
  :: remove files that are older than 31 days (retention period)
  forfiles /s /d -31 /c "cmd /c if @isdir==FALSE del @relpath")
  
  :: attempt to remove folders (will fail if the folder is not empty.)
  forfiles /s /d -31 /c "cmd /c if @isdir==TRUE rd @relpath"
  </code></pre>
  
  <p>The above script will only remove the deepest folder. I suppose I could execute forfiles 8 times in a row, but that's a serious waste of resources.</p>