用 forfiles 删除 N 天前的旧文件

Windows 里被遗忘的 find -mtime 等价物——按文件年龄筛选并对其执行命令。

Windows清理文件命令提示符高风险
运行 forfiles /P <目录> /S /M *.log /D -30 /C "cmd /c del @path" 删除 30 天前的日志(先用 echo 测试)。

01命令

命令
$ forfiles /P "C:\Logs" /S /M *.log /D -30 /C "cmd /c echo @path"

02作用说明

/D -30 匹配最后修改时间在 30 天前的文件;/D -2026-09-01 指定具体日期,/D +7 表示 7 天以内。/S 递归子目录,/M 按掩码过滤,@path、@fname、@fdate、@ftime 会被代入 /C 命令。forfiles 是服务器上做日志保留的定时任务标准组件。

03风险

风险高风险
使用条件Windows Vista or later
!注意: 把 echo 换成 del 会永久删除所有匹配文件——务必先用 echo @path 跑一遍确认将删除的清单。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • FORFILES - Windows CMD
    SS64 · technical · 2026-09-17
    依据: SS64 documents /D -30 as files last modified more than 30 days ago, and shows "cmd /c del @path" as the standard deletion pattern.
  • forfiles | Microsoft Learn
    Microsoft · vendor-doc · 2026-09-17
    依据: Microsoft documents forfiles /D +/-n to select files with last-modified date older/newer than n days, /S for recursion, and /C to run a command per file with @path variables.

最后验证: 2026-09-17 · 分类: 文件与文件夹

06相关方案