Batch file to delete files older than N days

前端 未结 24 3197
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 11:11

I am looking for a way to delete all files older than 7 days in a batch file. I\'ve searched around the web, and found some examples with hundreds of lines of code, and oth

24条回答
  •  庸人自扰
    2020-11-21 11:45

    Ok was bored a bit and came up with this, which contains my version of a poor man's Linux epoch replacement limited for daily usage (no time retention):

    7daysclean.cmd

    @echo off
    setlocal ENABLEDELAYEDEXPANSION
    set day=86400
    set /a year=day*365
    set /a strip=day*7
    set dSource=C:\temp
    
    call :epoch %date%
    set /a slice=epoch-strip
    
    for /f "delims=" %%f in ('dir /a-d-h-s /b /s %dSource%') do (
        call :epoch %%~tf
        if !epoch! LEQ %slice% (echo DELETE %%f ^(%%~tf^)) ELSE echo keep %%f ^(%%~tf^)
    )
    exit /b 0
    
    rem Args[1]: Year-Month-Day
    :epoch
        setlocal ENABLEDELAYEDEXPANSION
        for /f "tokens=1,2,3 delims=-" %%d in ('echo %1') do set Years=%%d& set Months=%%e& set Days=%%f
        if "!Months:~0,1!"=="0" set Months=!Months:~1,1!
        if "!Days:~0,1!"=="0" set Days=!Days:~1,1!
        set /a Days=Days*day
        set /a _months=0
        set i=1&& for %%m in (31 28 31 30 31 30 31 31 30 31 30 31) do if !i! LSS !Months! (set /a _months=!_months! + %%m*day&& set /a i+=1)
        set /a Months=!_months!
        set /a Years=(Years-1970)*year
        set /a Epoch=Years+Months+Days
        endlocal& set Epoch=%Epoch%
        exit /b 0
    

    USAGE

    set /a strip=day*7 : Change 7 for the number of days to keep.

    set dSource=C:\temp : This is the starting directory to check for files.

    NOTES

    This is non-destructive code, it will display what would have happened.

    Change :

    if !epoch! LEQ %slice% (echo DELETE %%f ^(%%~tf^)) ELSE echo keep %%f ^(%%~tf^)
    

    to something like :

    if !epoch! LEQ %slice% del /f %%f
    

    so files actually get deleted

    February: is hard-coded to 28 days. Bissextile years is a hell to add, really. if someone has an idea that would not add 10 lines of code, go ahead and post so I add it to my code.

    epoch: I did not take time into consideration, as the need is to delete files older than a certain date, taking hours/minutes would have deleted files from a day that was meant for keeping.

    LIMITATION

    epoch takes for granted your short date format is YYYY-MM-DD. It would need to be adapted for other settings or a run-time evaluation (read sShortTime, user-bound configuration, configure proper field order in a filter and use the filter to extract the correct data from the argument).

    Did I mention I hate this editor's auto-formating? it removes the blank lines and the copy-paste is a hell.

    I hope this helps.

提交回复
热议问题