Batch file to delete files older than N days

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

    ROBOCOPY works great for me. Originally suggested my Iman. But instead of moving the files/folders to a temporary directory then deleting the contents of the temporary folder, move the files to the trash!!!

    This is is a few lines of my backup batch file for example:

    SET FilesToClean1=C:\Users\pauls12\Temp
    SET FilesToClean2=C:\Users\pauls12\Desktop\1616 - Champlain\Engineering\CAD\Backups
    
    SET RecycleBin=C:\$Recycle.Bin\S-1-5-21-1480896384-1411656790-2242726676-748474
    
    robocopy "%FilesToClean1%" "%RecycleBin%" /mov /MINLAD:15 /XA:SH /NC /NDL /NJH /NS /NP /NJS
    robocopy "%FilesToClean2%" "%RecycleBin%" /mov /MINLAD:30 /XA:SH /NC /NDL /NJH /NS /NP /NJS
    

    It cleans anything older than 15 days out of my 'Temp' folder and 30 days for anything in my AutoCAD backup folder. I use variables because the line can get quite long and I can reuse them for other locations. You just need to find the dos path to your recycle bin associated with your login.

    This is on a work computer for me and it works. I understand that some of you may have more restrictive rights but give it a try anyway;) Search Google for explanations on the ROBOCOPY parameters.

    Cheers!

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

    Gosh, a lot of answers already. A simple and convenient route I found was to execute ROBOCOPY.EXE twice in sequential order from a single Windows command line instruction using the & parameter.

    ROBOCOPY.EXE SOURCE-DIR TARGET-DIR *.* /MOV /MINAGE:30 & ROBOCOPY.EXE SOURCE-DIR TARGET-DIR *.* /MOV /MINAGE:30 /PURGE
    

    In this example it works by picking all files (.) that are older than 30 days old and moving them to the target folder. The second command does the same again with the addition of the PURGE command which means remove files in the target folder that don’t exist in the source folder. So essentially, the first command MOVES files and the second DELETES because they no longer exist in the source folder when the second command is invoked.

    Consult ROBOCOPY's documentation and use the /L switch when testing.

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

    I think e.James's answer is good since it works with unmodified versions of Windows as early as Windows 2000 SP4 (and possibly earlier), but it required writing to an external file. Here is a modified version that does not create an external text file while maintaining the compatibility:

    REM del_old.cmd
    REM usage: del_old MM-DD-YYYY
    setlocal enabledelayedexpansion
    for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do @if exist "%%~nxa" set "excludefiles=!excludefiles!;;%%~nxa;;"
    for /f "tokens=*" %%a IN ('dir /b') do @(@echo "%excludefiles%"|FINDSTR /C:";;%%a;;">nul || if exist "%%~nxa" DEL /F /Q "%%a">nul 2>&1)
    

    To be true to the original question, here it is in a script that does ALL the math for you if you call it with the number of days as the parameter:

    REM del_old_compute.cmd
    REM usage: del_old_compute N
    setlocal enabledelayedexpansion
    set /a days=%1&set cur_y=%DATE:~10,4%&set cur_m=%DATE:~4,2%&set cur_d=%DATE:~7,2%
    for /f "tokens=1 delims==" %%a in ('set cur_') do if "!%%a:~0,1!"=="0" set /a %%a=!%%a:~1,1!+0
    set mo_2=28&set /a leapyear=cur_y*10/4
    if %leapyear:~-1% equ 0 set mo_2=29
    set mo_1=31&set mo_3=31&set mo_4=30&set mo_5=31
    set mo_6=30&set mo_7=31&set mo_8=31&set mo_9=30
    set mo_10=31&set mo_11=30&set mo_12=31
    set /a past_y=(days/365)
    set /a monthdays=days-((past_y*365)+((past_y/4)*1))&&set /a past_y=cur_y-past_y&set months=0
    :setmonth
    set /a minusmonth=(cur_m-1)-months
    if %minusmonth% leq 0 set /a minusmonth+=12
    set /a checkdays=(mo_%minusmonth%)
    if %monthdays% geq %checkdays% set /a months+=1&set /a monthdays-=checkdays&goto :setmonth
    set /a past_m=cur_m-months
    set /a lastmonth=cur_m-1
    if %lastmonth% leq 0 set /a lastmonth+=12
    set /a lastmonth=mo_%lastmonth%
    set /a past_d=cur_d-monthdays&set affffdays=::
    if %past_d% leq 0 (set /a past_m-=1&set affffdays=)
    if %past_m% leq 0 (set /a past_m+=12&set /a past_y-=1)
    set mo_2=28&set /a leapyear=past_y*10/4
    if %leapyear:~-1% equ 0 set mo_2=29
    %affffdays%set /a past_d+=mo_%past_m%
    set d=%past_m%-%past_d%-%past_y%
    for /f "tokens=*" %%a IN ('xcopy *.* /d:%d% /L /I null') do @if exist "%%~nxa" set "excludefiles=!excludefiles!;;%%~nxa;;"
    for /f "tokens=*" %%a IN ('dir /b') do @(@echo "%excludefiles%"|FINDSTR /C:";;%%a;;">nul || if exist "%%~nxa" DEL /F /Q "%%a">nul 2>&1)
    

    NOTE: The code above takes into account leap years, as well as the exact number of days in each month. The only maximum is the total number of days there have been since 0/0/0 (after that it returns negative years).

    NOTE: The math only goes one way; it cannot correctly get future dates from negative input (it will try, but will likely go past the last day of the month).

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

    My command is

    forfiles -p "d:\logs" -s -m*.log -d-15 -c"cmd /c del @PATH\@FILE" 
    

    @PATH - is just path in my case, so I had to use @PATH\@FILE

    also forfiles /? not working for me too, but forfiles (without "?") worked fine.

    And the only question I have: how to add multiple mask (for example ".log|.bak")?

    All this regarding forfiles.exe that I downloaded here (on win XP)

    But if you are using Windows server forfiles.exe should be already there and it is differs from ftp version. That is why I should modify command.

    For Windows Server 2003 I'm using this command:

    forfiles -p "d:\Backup" -s -m *.log -d -15 -c "cmd /c del @PATH"
    
    0 讨论(0)
  • 2020-11-21 11:58

    IMO, JavaScript is gradually becoming a universal scripting standard: it is probably available in more products than any other scripting language (in Windows, it is available using the Windows Scripting Host). I have to clean out old files in lots of folders, so here is a JavaScript function to do that:

    // run from an administrator command prompt (or from task scheduler with full rights):  wscript jscript.js
    // debug with:   wscript /d /x jscript.js
    
    var fs = WScript.CreateObject("Scripting.FileSystemObject");
    
    clearFolder('C:\\temp\\cleanup');
    
    function clearFolder(folderPath)
    {
        // calculate date 3 days ago
        var dateNow = new Date();
        var dateTest = new Date();
        dateTest.setDate(dateNow.getDate() - 3);
    
        var folder = fs.GetFolder(folderPath);
        var files = folder.Files;
    
        for( var it = new Enumerator(files); !it.atEnd(); it.moveNext() )
        {
            var file = it.item();
    
            if( file.DateLastModified < dateTest)
            {
                var filename = file.name;
                var ext = filename.split('.').pop().toLowerCase();
    
                if (ext != 'exe' && ext != 'dll')
                {
                    file.Delete(true);
                }
            }
        }
    
        var subfolders = new Enumerator(folder.SubFolders);
        for (; !subfolders.atEnd(); subfolders.moveNext())
        {
            clearFolder(subfolders.item().Path);
        }
    }
    

    For each folder to clear, just add another call to the clearFolder() function. This particular code also preserves exe and dll files, and cleans up subfolders as well.

    0 讨论(0)
  • 2020-11-21 12:01

    Enjoy:

    forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"
    

    See forfiles documentation for more details.

    For more goodies, refer to An A-Z Index of the Windows XP command line.

    If you don't have forfiles installed on your machine, copy it from any Windows Server 2003 to your Windows XP machine at %WinDir%\system32\. This is possible since the EXE is fully compatible between Windows Server 2003 and Windows XP.

    Later versions of Windows and Windows Server have it installed by default.

    For Windows 7 and newer (including Windows 10):

    The syntax has changed a little. Therefore the updated command is:

    forfiles /p "C:\what\ever" /s /m *.* /D -<number of days> /C "cmd /c del @path"
    
    0 讨论(0)
提交回复
热议问题