Batch file to delete files older than N days

前端 未结 24 2299
没有蜡笔的小新
没有蜡笔的小新 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.

    0 讨论(0)
  • 2020-11-21 11:45

    For windows 2012 R2 the following would work:

        forfiles /p "c:\FOLDERpath" /d -30 /c "cmd /c del @path"
    

    to see the files which will be deleted use this

        forfiles /p "c:\FOLDERpath" /d -30 /c "cmd /c echo @path @fdate"
    
    0 讨论(0)
  • 2020-11-21 11:50

    This one did it for me. It works with a date and you can substract the wanted amount in years to go back in time:

    @echo off
    
    set m=%date:~-7,2%
    set /A m
    set dateYear=%date:~-4,4%
    set /A dateYear -= 2
    set DATE_DIR=%date:~-10,2%.%m%.%dateYear% 
    
    forfiles /p "C:\your\path\here\" /s /m *.* /d -%DATE_DIR% /c "cmd /c del @path /F"
    
    pause
    

    the /F in the cmd /c del @path /F forces the specific file to be deleted in some the cases the file can be read-only.

    the dateYear is the year Variable and there you can change the substract to your own needs

    0 讨论(0)
  • 2020-11-21 11:51

    Have a look at my answer to a similar question:

    REM del_old.bat
    REM usage: del_old MM-DD-YYY
    for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> FILES_TO_KEEP.TXT
    for /f "tokens=*" %%a IN ('xcopy *.* /L /I /EXCLUDE:FILES_TO_KEEP.TXT null') do if exist "%%~nxa" del "%%~nxa"
    

    This deletes files older than a given date. I'm sure it can be modified to go back seven days from the current date.

    update: I notice that HerbCSO has improved on the above script. I recommend using his version instead.

    0 讨论(0)
  • 2020-11-21 11:52

    My script to delete files older than a specific year :

    @REM _______ GENERATE A CMD TO DELETE FILES OLDER THAN A GIVEN YEAR
    @REM _______ (given in _olderthanyear variable)
    @REM _______ (you must LOCALIZE the script depending on the dir cmd console output)
    @REM _______ (we assume here the following line's format "11/06/2017  15:04            58 389 SpeechToText.zip")
    
    @set _targetdir=c:\temp
    @set _olderthanyear=2017
    
    @set _outfile1="%temp%\deleteoldfiles.1.tmp.txt"
    @set _outfile2="%temp%\deleteoldfiles.2.tmp.txt"
    
      @if not exist "%_targetdir%" (call :process_error 1 DIR_NOT_FOUND "%_targetdir%") & (goto :end)
    
    :main
      @dir /a-d-h-s /s /b %_targetdir%\*>%_outfile1%
      @for /F "tokens=*" %%F in ('type %_outfile1%') do @call :process_file_path "%%F" %_outfile2%
      @goto :end
    
    :end
      @rem ___ cleanup and exit
      @if exist %_outfile1% del %_outfile1%
      @if exist %_outfile2% del %_outfile2%
      @goto :eof
    
    :process_file_path %1 %2
      @rem ___ get date info of the %1 file path
      @dir %1 | find "/" | find ":" > %2
      @for /F "tokens=*" %%L in ('type %2') do @call :process_line "%%L" %1
      @goto :eof
    
    :process_line %1 %2
      @rem ___ generate a del command for each file older than %_olderthanyear%
      @set _var=%1
      @rem  LOCALIZE HERE (char-offset,string-length)
      @set _fileyear=%_var:~0,4%
      @set _fileyear=%_var:~7,4%
      @set _filepath=%2
      @if %_fileyear% LSS %_olderthanyear% echo @REM %_fileyear%
      @if %_fileyear% LSS %_olderthanyear% echo @del %_filepath%
      @goto :eof
    
    :process_error %1 %2
      @echo RC=%1 MSG=%2 %3
      @goto :eof
    
    0 讨论(0)
  • 2020-11-21 11:52

    More flexible way is to use FileTimeFilterJS.bat:

    @echo off
    
    ::::::::::::::::::::::
    set "_DIR=C:\Users\npocmaka\Downloads"
    set "_DAYS=-5"
    ::::::::::::::::::::::
    
    for /f "tokens=* delims=" %%# in ('FileTimeFilterJS.bat  "%_DIR%" -dd %_DAYS%') do (
        echo deleting  "%%~f#"
        echo del /q /f "%%~f#"
    )
    

    The script will allow you to use measurements like days, minutes ,seconds or hours. To choose weather to filter the files by time of creation, access or modification To list files before or after a certain date (or between two dates) To choose if to show files or dirs (or both) To be recursive or not

    0 讨论(0)
提交回复
热议问题