batch-file - 如何使用cmd/批处理文件删除目录中名为x的所有文件夹

标签 batch-file cmd

我有一个名为 x 的文件夹,其中包含许多子文件夹和文件。我想删除 x 中存在的名为 y 的文件夹及其所有子文件夹。必须删除的所述文件夹可能包含也可能不包含任何文件。我相信我可以使用 cmd 或某种批处理文件来做到这一点,但我是一个命令行新人,确实可以使用一些帮助。

一个简单的事情是读取文件夹的名称,这很有效,但我相信有比单独删除每个文件夹更好的方法..就像遍历所有文件夹的循环一样。

谢谢

编辑:只是为了澄清一下,我在 x 中有 y (需要删除的文件夹),它可以位于 x 的任何子文件夹中并且处于任何深度级别。我也在寻找答案,我可能需要一些时间才能接受任何答案。请耐心等待:)

最佳答案

这是另一个解决方案,用于描述脚本的每个部分:

@Echo OFF
REM Important that Delayed Expansion is Enabled
setlocal enabledelayedexpansion
REM This sets what folder the batch is looking for and the root in which it starts the search:
set /p foldername=Please enter the foldername you want to delete: 
set /p root=Please enter the root directory (ex: C:\TestFolder)
REM Checks each directory in the given root
FOR /R %root% %%A IN (.) DO (
    if '%%A'=='' goto end   
    REM Correctly parses info for executing the loop and RM functions
    set dir="%%A"
    set dir=!dir:.=!
    set directory=%%A
    set directory=!directory::=!
    set directory=!directory:\=;!   
    REM Checks each directory
    for /f "tokens=* delims=;" %%P in ("!directory!") do call :loop %%P
)
REM After each directory is checked the batch will allow you to see folders deleted.
:end
pause
endlocal
exit
REM This loop checks each folder inside the directory for the specified folder name. This allows you to check multiple nested directories.
:loop
if '%1'=='' goto endloop
if '%1'=='%foldername%' (
    rd /S /Q !dir!
    echo !dir! was deleted.
)
SHIFT
goto :loop
:endloop

如果您不想收到提示,可以将初始变量前面的 /p 去掉,然后在 = 后面输入它们的值:

set foldername=
set root=

您还可以删除循环部分中的 echo 和结束部分中的 pause,以便批处理静默运行。

它可能有点复杂,但代码可以应用于许多其他用途。

我测试了它,在 C:\Test 中查找相同文件夹名称 qwerty 的多个实例:

C:\Test\qwerty
C:\Test\qwerty\subfolder
C:\Test\test\qwerty
C:\Test\test\test\qwerty

剩下的就是:

C:\Test\
C:\Test\test\
C:\Test\test\test\

关于batch-file - 如何使用cmd/批处理文件删除目录中名为x的所有文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10393082/

相关文章:

Windows 批处理文件无法定位文件

windows - 批处理文件的 MID 函数

Windows 问题上的 java -cp

java - 通过从 Java 执行 PowerShell 脚本来终止服务

windows - 远程获取硬盘和处理器规范的命令

windows - 为什么 XCOPY/W 和 REPLACE/W 为它们的单字符提示消耗所有重定向的文本数据?

SVN 使用批处理文件获取今天的日志。

windows - 使用批处理脚本检查环境中是否存在 JAVA_HOME

windows - 如果我的 OEMCP 设置为 437 那么为什么我的 cmd.exe 默认代码页是 932?我该如何解决这个问题?

windows - 以纯文本格式导出注册表