batch file remove all but the newest 10 files

2019-02-24 19:10发布

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 IN ('DIR /a:-d /b /o:-d /t:c %1*.zip ^2^>nul') DO IF EXIST "%%~fA" ECHO "%%~fA" >>%LOGFILE%
FOR /f "skip=14 delims=" %%A IN ('DIR /a:-d /b /o:-d /t:c %1*.zip ^2^>nul') DO IF EXIST "%%~fA" DEL "%%~fA" >>%LOGFILE%
FOR /f "skip=14 delims=" %%A IN ('DIR /a:-d /b /o:-d /t:c %1*.log ^2^>nul') DO IF EXIST "%%~fA" ECHO "%%~fA" >>%LOGFILE%
FOR /f "skip=14 delims=" %%A IN ('DIR /a:-d /b /o:-d /t:c %1*.log ^2^>nul') DO IF EXIST "%%~fA" DEL "%%~fA" >>%LOGFILE%
IF [%3]==[Y] GOTO SECONDBACKUPDIR
IF [%3]==[y] GOTO SECONDBACKUPDIR
GOTO END

The problem I ran in to is that the backup was not running for a couple of weeks and ended up deleting all of my backups since they were over 2 weeks old.

What I need is for it to keep the last 10 latest backups.

Anyone have an idea how I would do that? I did not write this once since I'm not that familiar with batch files.

2条回答
来,给爷笑一个
2楼-- · 2019-02-24 19:12

You could use FOR /F SKIP to ignore the last 10 most recently modified entries after sorting by last modified date:

for /f "skip=10 eol=: delims=" %%F in ('dir /b /o-d *.zip') do @del "%%F"
查看更多
Explosion°爆炸
3楼-- · 2019-02-24 19:16

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%
查看更多
登录 后发表回答