Batch file to delete files older than N days

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

    this is nothing amazing, but i needed to do something like this today and run it as scheduled task etc.

    batch file, DelFilesOlderThanNDays.bat below with sample exec w/ params:

    DelFilesOlderThanNDays.bat 7 C:\dir1\dir2\dir3\logs *.log

    echo off
    cls
    Echo(
    SET keepDD=%1
    SET logPath=%2 :: example C:\dir1\dir2\dir3\logs
    SET logFileExt=%3
    SET check=0
    IF [%3] EQU [] SET logFileExt=*.log & echo: file extention not specified (default set to "*.log")
    IF [%2] EQU [] echo: file directory no specified (a required parameter), exiting! & EXIT /B 
    IF [%1] EQU [] echo: number of days not specified? :)
    echo(
    echo: in path [ %logPath% ]
    echo: finding all files like [ %logFileExt% ]
    echo: older than [ %keepDD% ] days
    echo(
    ::
    ::
    :: LOG
    echo:  >> c:\trimLogFiles\logBat\log.txt
    echo: executed on %DATE% %TIME% >> c:\trimLogFiles\logBat\log.txt
    echo: ---------------------------------------------------------- >> c:\trimLogFiles\logBat\log.txt
    echo: in path [ %logPath% ] >> c:\trimLogFiles\logBat\log.txt
    echo: finding all files like [ %logFileExt% ] >> c:\trimLogFiles\logBat\log.txt
    echo: older than [ %keepDD% ] days >> c:\trimLogFiles\logBat\log.txt
    echo: ---------------------------------------------------------- >> c:\trimLogFiles\logBat\log.txt
    ::
    FORFILES /p %logPath% /s /m %logFileExt% /d -%keepDD% /c "cmd /c echo @path" >> c:\trimLogFiles\logBat\log.txt 2<&1
    IF %ERRORLEVEL% EQU 0 (
     FORFILES /p %logPath% /s /m %logFileExt% /d -%keepDD% /c "cmd /c echo @path"
    )
    ::
    ::
    :: LOG
    IF %ERRORLEVEL% EQU 0 (
     echo:  >> c:\trimLogFiles\logBat\log.txt
     echo: deleting files ... >> c:\trimLogFiles\logBat\log.txt
     echo:  >> c:\trimLogFiles\logBat\log.txt
     SET check=1
    )
    ::
    ::
    IF %check% EQU 1 (
     FORFILES /p %logPath% /s /m %logFileExt% /d -%keepDD% /c "cmd /c del @path"
    )
    ::
    :: RETURN & LOG
    ::
    IF %ERRORLEVEL% EQU 0 echo: deletion successfull! & echo: deletion successfull! >> c:\trimLogFiles\logBat\log.txt
    echo: ---------------------------------------------------------- >> c:\trimLogFiles\logBat\log.txt
    

提交回复
热议问题