Batch file to delete files older than N days

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

    Expanding on aku's answer, I see a lot of people asking about UNC paths. Simply mapping the unc path to a drive letter will make forfiles happy. Mapping and unmapping of drives can be done programmatically in a batch file, for example.

    net use Z: /delete
    net use Z: \\unc\path\to\my\folder
    forfiles /p Z: /s /m *.gz /D -7 /C "cmd /c del @path"
    

    This will delete all files with a .gz extension that are older than 7 days. If you want to make sure Z: isn't mapped to anything else before using it you could do something simple as

    net use Z: \\unc\path\to\my\folder
    if %errorlevel% equ 0 (
        forfiles /p Z: /s /m *.gz /D -7 /C "cmd /c del @path"
    ) else (
        echo "Z: is already in use, please use another drive letter!"
    )
    
    0 讨论(0)
  • 2020-11-21 11:38

    For Windows Server 2008 R2:

    forfiles /P c:\sql_backups\ /S /M *.sql /D -90 /C "cmd /c del @PATH"
    

    This will delete all .sql files older than 90 days.

    0 讨论(0)
  • 2020-11-21 11:39
    forfiles /p "v:" /s /m *.* /d -3 /c "cmd /c del @path"
    

    You should do /d -3 (3 days earlier) This works fine for me. So all the complicated batches could be in the trash bin. Also forfiles don't support UNC paths, so make a network connection to a specific drive.

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

    You might be able to pull this off. You can take a look at this question, for a simpler example. The complexity comes, when you start comparing the dates. It may be easy to tell if the date is greater or not, but there are many situations to consider if you need to actually get the difference between two dates.

    In other words - don't try to invent this, unless you really can't use the third party tools.

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

    Use forfiles.

    There are different versions. Early ones use unix style parameters.

    My version (for server 2000 - note no space after switches)-

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

    To add forfiles to XP, get the exe from ftp://ftp.microsoft.com/ResKit/y2kfix/x86/

    and add it to C:\WINDOWS\system32

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

    If you have the XP resource kit, you can use robocopy to move all the old directories into a single directory, then use rmdir to delete just that one:

    mkdir c:\temp\OldDirectoriesGoHere
    robocopy c:\logs\SoManyDirectoriesToDelete\ c:\temp\OldDirectoriesGoHere\ /move /minage:7
    rmdir /s /q c:\temp\OldDirectoriesGoHere
    
    0 讨论(0)
提交回复
热议问题