Batch file to delete files older than N days

前端 未结 24 2536
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  旧时难觅i
    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!"
    )
    

提交回复
热议问题