windows 删除超过 X 天的文件的批处理脚本(基于创建日期,而不是修改日期)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17785216/
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-09 10:44:19  来源:igfitidea点击:

Batch script to delete files older than X days (based on creation date, not modified date)

windowsbatch-filescheduled-tasks

提问by Francesco

On a windows machine (win 7 or Win server 2008 R2) I have a batch script that copies some .config files to a backup folder.
I want to write another script that deletes the backup files created a week earlier.

在 Windows 机器(win 7 或 Win server 2008 R2)上,我有一个批处理脚本将一些 .config 文件复制到备份文件夹。
我想编写另一个脚本来删除一周前创建的备份文件。

There are plenty of suggestions on how to use FORFILES(as example):

有很多关于如何使用的建议FORFILES(例如):

FORFILES /P "D:\Configs_Backup" /M *.config /D -7 /C "cmd /c del @file"

But this command uses the "modified" timestamp, while I need to use the creation date.

但是这个命令使用“修改过的”时间戳,而我需要使用创建日期。

Without installing any third party program, is it possible via command console to achieve this?

不安装任何第三方程序,是否可以通过命令控制台来实现?

回答by Endoro

try this, look at the output and remove the echo, if it looks good:

试试这个,看看输出并删除它echo,如果它看起来不错:

@ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
SET /a XDay=7
CALL :DateToJDN "%DATE%" JDNToday
FOR /r "D:\Configs_Backup" %%a IN (*.config) DO (
    FOR /f "tokens=1,4*" %%b IN ('dir /tc "%%~a"^|findstr "^[0-9]"') DO (
        CALL :DateToJDN "%%b" filedate
        SET /a diffdays=JDNToday-filedate
        IF !diffdays! gtr %XDay% ECHO DEL /F /Q "%%~a"
        )
    )
GOTO :eof

:DateToJDN "DD mm/dd/yyyy" jdn=
setlocal
set date=%~1
set /A yy=%date:~-4%, mm=1%date:~-10,2% %% 100, dd=1%date:~-7,2% %% 100
set /A a=mm-14, jdn=(1461*(yy+4800+a/12))/4+(367*(mm-2-12*(a/12)))/12-(3*((yy+4900+a/12)/100))/4+dd-32075
endlocal & set %2=%jdn%
exit /B

Note: this works only for AM/PMtime format.

注意:这仅适用于AM/PM时间格式。

回答by foxidrive

See if this helps - Keep the 5 *.config files (skip=5) with the most recent creation date
Test it on sample files.

看看这是否有帮助 - 保留 5 个 *.config 文件 (skip=5) 的最新创建日期
在示例文件上测试它。

@echo off
pushd "d:\folder"
   del file2.tmp 2>nul
   for /f "delims=" %%a in ('dir *.config /b /a-d ') do call :getcreationdate "%%~fa"
   sort /r <file2.tmp >file.tmp
   for /f "skip=5 tokens=1,*" %%a in (file.tmp) do del "%%~b"
   del file.tmp file2.tmp 
popd
pause
goto :EOF

 :getcreationdate
 set "file=%~1"
 set "file=%file:\=\%"
 WMIC DATAFILE WHERE name="%file%" get creationdate | find "." >file.tmp
 for /f %%b in (file.tmp) do set dt=%%b
 set dt=%dt:~0,8%_%dt:~8,6%
 del file.tmp
 >>file2.tmp echo %dt% "%~1"