windows 如何使用 forfile(或类似的)删除超过 n 天的文件,但始终保留最近的 n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2691266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:19:34  来源:igfitidea点击:

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

windowsbatch-filefor-loopscriptingforfiles

提问by Aidan Whitehall

(Using Windows 2000 and 2003 Server)

(使用 Windows 2000 和 2003 服务器)

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

我们使用 forfiles.exe 删除超过 n 天的备份 .zip 文件,效果很好(命令有点像下面)

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:

如果无法创建 .zip 文件,我想确保 5 天后备份中不会出现 0 个 .zip 文件。因此,命令需要是:

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

“删除任何早于 5 天的文件,但始终保留最近的 5 个文件,即使它们本身早于 5 天”

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

我们可以使用 forfiles.exe 或其他解决方案(尽管任何光滑的单行代码总是比脚本文件更可取)。

Thanks!

谢谢!

回答by MatsT

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.

将删除除 5 个最新文件之外的所有文件。我找不到一种单行程序来使所有文件的更新时间都超过 5 天,因此您可能不得不使用一些更复杂的逻辑。

/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).

跳过前 5 行(5 最新行)。

回答by aschipfl

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:

这个小脚本会删除超过 5 天的匹配文件,或者更准确地说,至少 6 天前修改过的文件,但始终至少保留 5 个最近修改的文件:

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
)