Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

@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/PM time format.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...