title: Batch Script to delete oldest folder in a given folder
body: <p>I'm writing a simple .bat backup script, and as part of it I want the oldest backup (folder) to be deleted upon reaching a set max limit of backups.</p>
  
  <p>Right now I have this: </p>
  
  <p><code>%COUNTER%</code> is based on the number of backup folders currently in the directory where backups are stored, and is calculated earlier in the script.</p>
  
  <p><code>%MAXBACKUPS%</code> is just a user-specified number like "10," to say that you only want to keep up to 10 versions of the backups.</p>
  
  <pre><code>:: Delete the oldest backup, but only if we've exceeded the desired number of backups.
  IF %COUNTER% gtr %MAXBACKUPS% (
  ECHO More than %MAXBACKUPS% backups exist. Deleting oldest...
  FOR /f "delims=" %%a in ('dir "..\Backup\*" /t:c /a:d /o:-d /b') do rd /s /q "..\Backup\%%a"
  ::Increment the counter down since we've just removed a backup folder.
  SET /a COUNTER=%COUNTER%-1
  )
  </code></pre>
  
  <p>I would like this script to only delete the one oldest folder in the <code>..\Backup</code> folder, but as it stands it seems to delete every single folder it finds once it reaches the backup limit, which is obviously not the desired behavior.</p>