There are often scenarios such as rolling backups or rolling logfiles where I create folders which have the date in the folder name.
HINT: Using the format YYYYMMDD means that an alphabetic search is also chronological!
In most cases I only want to keep a certain number of these folders and delete the older ones. The following script will implement this deletion process.
setlocal ENABLEDELAYEDEXPANSION set Count=0 for /F "usebackq" %%D in (`dir /b /ad /o-n %TargetRoot%\????????`) do ( set /a Count+=1 if !Count! leq 5 ( echo !Count! keep folder %%D ) else ( echo !Count! delete folder %%D rmdir /s /q %TargetRoot%\%%D ) )
https://github.com/RossGoodman/DOS/blob/master/KeepRecentFolders.cmd
In this case %TargetRoot% is the folder that contains the folders to be deleted and I’m searching (dir) for directories that are eight characters long (???????? will match YYYYMMDD) in chronological order with the most recent first.
Loop round the results on folder at a time, incrementing a counter, if the counter is less than or equal to a threshold value 5 in the case above (to keep six folders) then the script does nothing, otherwise it removes the folder.
See also this script for how to create folders named with the current date format.