Home > Enterprise >  Batch file to delete more than a specific number of files
Batch file to delete more than a specific number of files

Time:04-19

I know how to create a batch file to delete files older than a certain date but is there a way to delete the oldest files more than a certain number? For example if there are 3 files in a directory can you delete the oldest files keeping only the 2 latest? This will delete files older than 3 days but how to modify that so it will delete the oldest files more than 3 in that directory. forfiles /p "D:\Daily Backups\myfiles" /s /d -3 /c "cmd /c del @file"

CodePudding user response:

Get a list of all files ordered from new to old. Then loop through this list, ignoring the first three files and delete everything else.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a counter=1

REM get an ordered list of all files from newest to oldest
REM you may want to edit the directory and filemask

FOR /f "delims=" %%a IN (
    'dir /b /a-d /tw /o-d "backups\*.*"'
) DO (
    
    REM only if the counter is greater than 3 call the deletefile subroutine
    IF !counter! GTR 3 (
        CALL :deletefile %%a
    ) ELSE (
        ECHO KEEPING FILE: %%a
    )

    SET /a counter=!counter! 1
)

GOTO end

:deletefile
ECHO DELETING FILE: %1
REM DEL /F /Q %1   <-- enable this to really delete the file
GOTO :EOF

:end
SETLOCAL DISABLEDELAYEDEXPANSION
ECHO Script done!
  • Related