Search code examples
datebatch-filebackupdirectory

Batch file delete oldest folder if there are more than 3 folders in root


I have now a batch file where all folders older then 22 days will be deleted. When the batch file is running every week there is no problem, there will always be four folders in the root. But when there is holiday, the system is turned off up to three weeks. When the file is running after that holiday, there will be deleted three folders.

I am now searching for a command where only the oldest folder will be deleted, so I will keep four folders for backup at all time.

The folders are named like backup_YYYY-MM-DD.


Solution

  • This task can be easily done by using the following batch code with more or less a single command line:

    @echo off
    for /F "skip=4 eol=| delims=" %%I in ('dir "C:\Temp\backup_????-??-??" /AD /B /O-N 2^>nul') do rd /Q /S "C:\Temp\%%I"
    

    The command DIR returns because of option /AD just directory names (attribute directory) in bare format because of option /B and ordered reverse by name because of option /O-N found in the directory C:\Temp with a name matched by the wildcard pattern backup_????-??-??.

    The reverse order by name results automatically also in a reverse order by date on using the date format YYYY-MM-DD in the folder names. The name of the newest backup folder is output first and the name of the oldest folder is output last by command DIR.

    The command FOR skips the first four lines of output of command DIR and therefore ignores the four newest backup folders. All other backup folders are processed by FOR resulting in removing them with command RD. There is nothing to process by FOR if there are not at least five folders found by DIR with name matching the pattern backup_????-??-??. So there are always at least four backup folders, except a user deletes backup folders manually.

    The command DIR outputs an error message to STDERR if it can't find any folder matching the pattern backup_????-??-??. This error message is suppressed with 2>nul by redirecting the error message from STDERR to device NUL. The redirection operator > must be escaped here with ^ as otherwise the Windows command processor would interpret > as redirection for command FOR positioned wrong which would result in a syntax error message.

    Note: Command DIR returns here just the backup folder names without path and therefore the parent folder path must be written twice in code, on command DIR and also on command RD.

    For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

    • echo /?
    • dir /?
    • for /?
    • rd /?

    And see also the Microsoft documentation about Using command redirection operators.