繁体   English   中英

批处理脚本可自动删除空文件夹-需要帮助添加例外

[英]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中的以下文件夹结构上进行了测试

  • 文件夹1
    • 要删除的文件夹
    • 保留文件夹
    • FolderToKeepB
  • 资料夹2
    • 保留文件夹
    • 非空文件夹
      • Folder.txt中的文件

运行下面的批处理文件后,结果文件夹结构为

  • 文件夹1
    • 保留文件夹
    • FolderToKeepB
  • 资料夹2
    • 保留文件夹
    • 非空文件夹
      • Folder.txt中的文件

删除了一个文件夹“要删除的文件夹” ,因为此文件不应该始终保留,并且确实为空。

@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

有关使用的命令的更多详细信息,请在运行时阅读打印在控制台窗口中的帮助输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM