不要使用该/S
选项,forfiles
只处理子子文件夹,然后删除顶级文件夹以防所有找到的文件至少 30 天(意味着它们最后一次修改是在 30 天前或更早):
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_ROOT=U:\TEST\top" & rem // (full path to top-level directory)
set "_LEV1=*" & rem // (name or mask of sub-directory)
set "_LEV2=*" & rem // (name or mask of sub-sub-directory)
set "_MASK=*" & rem // (mask for files in sub-sub-directory)
set /A "_AGE=30" & rem // (age in number of days of the files)
rem // Initialise counter for files that are newer than the given age:
set /A "SUM=0"
rem // Iterate through all matching sub-directories of the top-level directory:
for /D %%A in ("%_ROOT%\%_LEV1%") do (
rem // Iterate through all matching sub-sub-directories of the current sub-directory:
for /D %%B in ("%%~A\%_LEV2%") do (
rem // Initialise an auxiliary flag that indicates whether the following loop iterates the second time:
set "FLAG="
rem /* In the following `for /F` loop two `forfiles` command lines are executed in order to retrieve the
rem number of matching files in the current sub-sub-directory that are newer than the given age;
rem since `forfiles` cannot return files newer than a given age (since `/D +` points to the future!),
rem let us determine the diffenence between the numbers of all files and such older than the given age;
rem the condition `if @isdir==FALSE` is intentionally omitted in the first `forfiles` command line,
rem because otherwise, sub-directories od the current sub-sub-directory would then become lost: */
for /F %%C in ('
rem/ /* Determine numbers of all files minus aged out files: */ ^& ^
2^> nul forfiles /P "%%~B" /M "%_MASK%" /C "cmd /C echo #" ^| find /C "#" ^& ^
2^> nul forfiles /P "%%~B" /M "%_MASK%" /D -%_AGE% /C "cmd /C if @isdir==FALSE echo #" ^| find /C "#"
') do (
rem /* The flag is not defined in the first iteration when all files are counted, but is is defined in
rem the second iteration when newer files are filtered out and the older ones are counted: */
if defined FLAG (set /A "SUM-=%%C") else set /A "SUM+=%%C" & set "FLAG=#"
)
)
rem // The following line is merely intended for debugging purposes and may be removed:
>&2 (for /F %%D in ('set /A "SUM"') do echo Processing "%%~nxA\%%~nxB": found %%D newer file^(s^) so far...)
)
rem // The following line does actually not delete anything unless you remove the upper-case `ECHO` statement:
if %SUM% equ 0 ECHO rd /S /Q "%_ROOT%"
endlocal
exit /B