![](/img/trans.png)
[英]I need a batch script that can delete all folders inside a directory, EXCLUDING certain folders
[英]Batch script to automatically delete empty folders - need help adding exceptions
我的批处理经验相当有限,但是我确实编写了以下脚本来删除目标文件夹的所有空子文件夹。
set "Target=C:\Target"
for /f "delims=" %%i in ('dir "%Target%" /A:D /B /S ^| sort /r') do rd "%%i" 2>NUL >NUL
我的问题是:
1.我希望能够保留第一层子文件夹,并仅删除随后几层中的空文件夹。
2.如果可能的话,我也想完全跳过某些文件夹的名称。
是否可以这样做,还是我需要为我要清理的所有子文件夹编写脚本?
下面的代码在文件夹C:\\ Target中的以下文件夹结构上进行了测试
运行下面的批处理文件后,结果文件夹结构为
仅删除了一个文件夹“要删除的文件夹” ,因为此文件夹不应该始终保留,并且确实为空。
@echo off
rem For each subfolder in C:\Target do ...
for /D %%D in ("C:\Target\*") do (
rem For each subfolder in found subfolder of C:\Target do ...
for /D %%S in ("%%~D\*") do call :DeleteFolder "%%~S"
)
rem This goto :EOF results in exiting the batch file.
goto :EOF
rem Subroutine for easier comparing the name of the current
rem subfolder with the name of the subfolders to always keep.
rem The goto :EOF commands below just exit the subroutine.
:DeleteFolder
if "%~nx1"=="Folder To Keep A" goto :EOF
if "%~nx1"=="FolderToKeepB" goto :EOF
rem Delete this subfolder which fails if it is not empty.
rem The error message is suppressed by redirecting output stream
rem stderr (standard error) with handle 2 to the NUL device.
rd "%~1" 2>nul
goto :EOF
有关使用的命令的更多详细信息,请在运行时阅读打印在控制台窗口中的帮助输出
call /?
或help call
for /?
或help for
goto /?
或help goto
rd /?
或help rd
或rmdir /?
或help rmdir
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.