批处理文件删除超过特定数量的文件

Batch file to delete more than a specific number of files

我知道如何创建批处理文件来删除早于特定日期的文件,但是有没有办法删除超过特定数量的最旧文件? 例如,如果目录中有 3 个文件,您可以删除最旧的文件只保留 2 个最新的文件吗? 这将删除超过 3 天的文件,但如何修改它以便删除该目录中超过 3 天的最旧文件。 forfiles /p "D:\Daily Backups\myfiles" /s /d -3 /c "cmd /c del @file"

获取所有文件的列表,从新到旧排序。 然后遍历此列表,忽略前三个文件并删除其他所有文件。

@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!