So your task is to delete older backup directories no longer needed.
The tricky solution would be working with "delete older than X days".
The simple solution is following:
@echo off
set "BackupDirectory=C:\Backup"
for /F "skip=7 delims=" %%D in ('dir "%BackupDirectory%" /AD /B /O-D 2^>nul') do (
rd /Q /S "%BackupDirectory%\%%D"
)
The command DIR returns a list which contains
- because of
/AD
(attribute directory) just the subdirectories and
- because of
/B
(bare format) just directory names and
- because of
/O-D
ordered by date with newest at top and oldest last.
The command FOR skips the first 7 lines from list, i.e. the 7 newest subdirectories, and executes on the other (older) directories the command to remove the subdirectory.
In your case with directory names starting with yyyy-mm-dd
it would be also possible to use /O-N
(ordered reverse by name) instead of /O-D
to keep skip=x newest subdirectories and delete all others.
Note: On NTFS partitions the last modification date of a folder changes if any file/folder in this folder is added/modified/deleted, but not on FAT16, FAT32 or exFAT partitions.
On DIR command line after /O-D
the option /TC can be added get output the directory list sorted reverse by creation date of the folders. But backup folders are usually not modified later after backup was created. It is a matter of opinion to keep the newest folders taking modifications in the folders into account or rate only folder creation time.
In my experience on deleting backups the date is not so important. Important is only limiting the number of backups to avoid filling a storage media. For example if a backup usually needs 5 GiB, the number of backups to keep might be 10 or 20, but if a backup usually needs only 500 KiB, the number could be increased to 100. The date does not matter, just the total amount of bytes required for the backups, as the limit is the storage media size and not the time span.
And for a log file with lines always appended on each execution of a backup operation, the size of the log file must be usually observed and not the time span on which lines are appended to same log file to avoid that the log file becomes larger and larger. Moving a log file with size > x KiB or MiB to *_old.log
with /Y
to overwrite an already existing *_old.log
and then redirect the new lines into a new log file is quite often the right strategy to have just 2 logs files (*.log
and *_old.log
) with a defined maximum file size containing log lines of the last x backup operations.