batch file remove all but the newest 10 files

后端 未结 2 1714
我在风中等你
我在风中等你 2021-01-20 17:55

I have the following in a batch file:

:REMOLDFILES
ECHO Removing files older than 14 days. >>%LOGFILE%
cd /d %BKUPDIR%
FOR /f \"skip=14 delims=\" %%A I         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 18:24

    You can get a listing of files in reverse order by modified date using the DIR command. Then you just tell your FOR loop to skip the first 10 (note your post code shows 14, but you ask for 10) entries, so whatever is processed is deleted.

    REM Update to 14 if needed.
    SET Keep=10
    FOR /F "usebackq tokens=* skip=%Keep% delims=" %%A IN (`DIR *.zip /B /O:-D /A:-D`) DO DEL "%%A">>%LOGFILE%
    

    Since you are unfamiliar with batch, you can test this command (to see what will be deleted instead of actually deleting it) by replacing DEL with ECHO.


    Edit

    Since you are also processing log files, why not just delete them in the same loop?

    REM Update to 14 if needed.
    SET Keep=10
    FOR /F "usebackq tokens=* skip=%Keep% delims=" %%A IN (`DIR *.zip /B /O:-D /A:-D`) DO (
        ECHO Processing: %%~nA
        REM Delete ZIP file.
        DEL "%%A"
        REM Delete LOG file.
        DEL "%%~nA.log"
    )>>%LOGFILE%
    

提交回复
热议问题