Delete folders except for the last …

For a long time I have been looking for a program, VBS script or a batch file that deletes folders including all subfolders . It should work in such a way that any number of folders should remain and all others that are older should be deleted. This is useful for data backups, for example, if only the last 5 or 10 backups should remain and everything else should remain.

Since I am reluctant to work with the timestamp or folder, I wanted to attach it to the folder name . This also makes sense, since many backup jobs or programs attach the backup date and possibly the time to the folder name. Like here for example:

  • Backup_2014_12_28
  • Backup_2014_12_29
  • Backup_2014_12_30
  • Backup_2014_12_31
  • Backup_2015_01_01
  • Backup_2015_01_02
  • Backup_2015_01_03
  • Backup_2015_01_04
  • Backup_2015_01_05
  • Backup_2015_01_06
  • Backup_2015_01_07
  • Backup_2015_01_08
  • Backup_2015_01_09
  • Backup_2015_01_10

In my case I wanted it to be such that only the latest 5 folders including all subfolders remain . So the folders “Backup_2014_12_28” – “Backup_2015_01_05” should be deleted.

All attempts that I have made have failed. It doesn’t work with Robocopy, it worked with VBS script, but the runtime was out of the question. All other tools that are freely available on the Internet did not work properly. After that I did some research on the internet and finally put together the following solution myself:

[mks_toggle title = “delete folder“ state = “open“]

 Echo delete all folders except the last ..... FOR / F "eol =; skip = 5 tokens = * delims =," %% i in ('dir d:  Sicherheit  Backup _ *. * / O: -N / b') do ( RMDIR / S / Q d:  fuse  %% i ) 

[/ mks_toggle]

This batch file fulfills exactly this purpose and deletes all folders except the 5 newest. The runtime is good, it will probably not be faster. Now I can add this batch file to the scheduler and so those backups or folders that are older than the last 5 are deleted every night.

ATTENTION: I take no responsibility for any errors or data loss. Please test well before commissioning and always ensure additional data backup.

administrator