我有一个名为 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/