Windows batch file delete files older than X days but leave a min of X files

穿精又带淫゛_ 提交于 2021-01-21 10:44:44

问题


I have see the older posts where you can delete files older than X days, such as this one Batch file to delete files older than N days. I'd like to add an additional filter to this so that if the backup I am running is not happening for 2 weeks, then it wouldn't delete all my backups.

I know with this:

forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"

That you can delete older than X days but how do I add the condition above and have it leave a minimum of Z files behind before it does the delete?

Example:

Lets say I want to delete files older than 14 days but keep a minimum of 5 files with the files below:

Jan 1 - backup1.zip
Jan 2 - backup2.zip
Jan 3 - backup3.zip
Jan 4 - backup4.zip
Jan 5 - backup5.zip
Jan 6 - backup6.zip
Jan 7-20 no backups done
Jan 21st - script runs and removed old files

With the example code that deletes all files older than 14 days, all of my backup files would be deleted and I'd be left with no backups. I'd like the script to see that only 6 files remains and keep a minimum of 5 files.

Make sense? Is this possible through windows batch files?

FOR CLARITY

This is part of my batch file that I have:

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%

The files are zip and log files that I am deleting and they all reside in the same folder.


回答1:


This script will delete all zip and log files older than 14 days, keeping a minimum of the 5 most recent of each (10 total), regardless of age.

Note that the FORFILES /D option is based on last modified date, so I did not use creation date for ordering my DIR command.

The FORFILES command is quite slow, so once I detect the a file older than 14 days old, I don't bother running FORFILES again, since I know all remaining files are that age or older.

@echo off
pushd "c:\yourBackupPath"
for %%X in (zip log) do (
  set "skip=1"
  for /f "skip=5 delims=" %%F in ('dir /b /a-d /o-d /tw *.%%X') do (
    if defined skip forfiles /d -14 /m "%%F" >nul 2>nul && set "skip="
    if not defined skip del "%%F" 
  )
)  


来源:https://stackoverflow.com/questions/31249192/windows-batch-file-delete-files-older-than-x-days-but-leave-a-min-of-x-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!