How to use forfiles (or similar) to delete files older than n days, but always leaving most recent n

耗尽温柔 提交于 2019-12-05 07:28:09

问题


(Using Windows 2000 and 2003 Server)

We use forfiles.exe to delete backup .zip files older than n days, and it works great (command is a bit like below)

forfiles -p"C:\Backup" -m"*.zip" -c"cmd /c if @ISDIR==FALSE del \"@PATH\@FILE\"" -d-5

If a .zip file fails to be created, I'd like to ensure that we don't end up with 0 .zip files in the backup after 5 days. Therefore, the command needs to be:

"delete anything older than 5 days, but ALWAYS keep the most recent 5 files, EVEN if they themselves are older than 5 days"

We can use forfiles.exe or another solution (although anything that is a slick one-liner is ALWAYS preferable to a script file).

Thanks!


回答1:


FOR /F "skip=5 delims=" %%G IN ('dir /b /O-D /A-D') DO del "%%G"

Will delete all files except the 5 newest ones. I couldn't find a one-liner to keep all files newer than 5 days so for that you might have to use some more complicated logic.

/b

Lists only file names without extra info

/O-D

Sorts list by reverse date order.

/A-D

Filters to only show non-directory files

skip=5

skips the 5 first lines (5 newest ones).




回答2:


This tiny script deletes matching files that are older than 5 days, or more precisely said, that have been modified at least 6 days ago, but always keeps at least the 5 most recently modified ones:

rem // Change to the target directory:
pushd "C:\Backup" && (
    rem // Loop through all matching files but skip the 5 most recently modified ones:
    for /F "skip=5 delims= eol=|" %%F in ('
        dir /B /A:-D /O:-D "*.zip"
    ') do (
        rem // Delete the currently iterated file only when modified at least 6 days ago:
        forfiles /P "%%~dpF." /M "%%~nxF" /D -6 /C "cmd /C ECHO del /F /A @PATH" 2> nul
    )
    rem // Restore the original working directory:
    popd
)


来源:https://stackoverflow.com/questions/2691266/how-to-use-forfiles-or-similar-to-delete-files-older-than-n-days-but-always-l

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