Home > database >  Batchfile to delete all folders but the latest AND a special folder
Batchfile to delete all folders but the latest AND a special folder

Time:03-26

hope you can help me. I am looking for a way to use batchscript to delete all folders in a subfolder except

  • the very newest folder AND
  • a special folder named "BACKUP".

So the backup folder can be older, but it needs to be kept. All other folders except the one with the newest date should be deleted.

There will be files in all of those folders, but there are no hidden files or subfolders, so this needs not to be considered in this case.

I found a lot of solutions here to either spare the backup folder or delete everything except the newest, but I cannot seem to find a solution that can do both.

for /d %%i in ("C:\Parent\*") do if /i not "%%~nxi"=="BACKUP" del /s /q "%%i"

I.e. like this, but it will not keep the newest folder. All the other folders except the backup folder have names like "20220215" "20210405".

Thank you for any help you can give.

KR Susanne

CodePudding user response:

set "skipme=Y"
for /f "delims=" %%b in ('dir /b /ad /od "c:\parent\*"') do if /i "%%b" neq "backup" if defined skipme (set "skipme=") else (ECHO rd /s /q "c:\parent\%%b")

Should remove all the required directories. Well, report the directorynames that would be delete if the echo keyword was deleted.

skipme is initialised to a value. for each directory found, with the exception of backup, check whether skipme has a value; set skipme to empty if it's set (which will only be for the first directory found that isn't backup from a date-ordered dir list), otherwise remove the directory.

CodePudding user response:

Build a list of directories by dir sorted by age from newest to oldest, filter out unwanted ones by findstr, then use for /F to iterate through the list but skip the very first item:

rem // Change into root directory:
pushd "C:\Parent" && (
    rem /* Loop through matching directories sorted by last modification date (due to `/T:W`)
    rem    in descending order and skip the very first (that is the lastly modified) item: */
    for /F "skip=1 delims= eol=|" %%I in ('
        dir /B /A:D-H-S /O:-D /T:W "????????" ^| findstr /V /I /X "BACKUP"
    ') do rd /S /Q "%%I"
    rem // Return from root directory:
    popd
)

Since del only deletes files, rd is used instead to delete (sub-)directories too rather than leaving behind empty (sub-)directory trees.

The line dir /B /A:D-H-S /O:-D /T:W "????????" ^| findstr /V /I /X "BACKUP" could be replaced by the following in order to do stricter filtering:

        dir /B /A:D-H-S /O:-D /T:W "????????" ^| findstr /I /X "[12][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]"
  • Related