windowsbatch-filescheduled-tasks

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?


Solution

  • 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.