首页 > 解决方案 > 批处理文件删除 X 天旧文件排除几个文件

问题描述

我想从目录中删除 X 天前的文件,但想排除特定文件(*例外)。我正在使用以下命令,但似乎对我不起作用。

for /f "delims=" %%a in ('forfiles /p "%userprofile%\.." /d -180 /c "cmd /c if @isdir==TRUE echo @file"^|findstr /vig:"%userprofile%\exception.txt"') do echo rd /s /q "%%~a"

标签: batch-file

解决方案


Instead of using ForFiles you could use RoboCopy:

@For /F "Tokens=*" %%A In ('RoboCopy "%UserProfile%\.." Null /L /MinAge:180 /NC /NDL /NJH /NJS /NP /NS /XF exception*') Do @Del "%%A"

Enter RoboCopy /? at the Command Prompt for its usage information.


After re-reading your question, together with your code, it isn't clear whether you're wanting to exclude files named, exception*, which is what my answer above does, or to exclude files as listed inside a file named exception.txt. If it's the latter then you'd need to build a string of your exclusions first to append to the /XF list.

If your file only contains a few relatively short exclusion masks then you may be able to do it like this:

@Echo Off
Set "EX="
For /F "UseBackQ Delims=" %%A In ("%UserProfile%\exception.txt") Do (
    If Not Defined EX (Set "EX=%%A ") Else Call Set "EX=%%EX%%%%A ")
For /F "Tokens=*" %%A In ('RoboCopy "%UserProfile%\.." Null /L /MinAge:180 /NC /NDL /NJH /NJS /NP /NS /XF %EX%') Do Del "%%A"

推荐阅读