如何使用cmd/batch文件删除目录中名称x的所有文件夹

Ach*_*har 8 cmd batch-file

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

一个简单的事情是找到文件夹的名称,这有用,但我相信有比单独删除每个文件夹更好的方法..就像一些遍历所有文件夹的循环.

谢谢

编辑:只是为了澄清,我有x(需要删除的文件夹)在x内部,它可以在任何x的子文件夹和任何深度级别.此外,我正在寻找答案,我可能需要一些时间来接受任何答案.请多多包涵 :)

ies*_*sou 7

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

@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
Run Code Online (Sandbox Code Playgroud)

你可以/p从初始变量前面取出,=如果你不想被提示,只需输入它们的值:

set foldername=
set root=
Run Code Online (Sandbox Code Playgroud)

您还可以删除echo循环部分和pause末尾部分,以便批处理静默运行.

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

我测试了它在寻找同样的文件夹名称的多个实例qwertyC:\Test:

C:\Test\qwerty
C:\Test\qwerty\subfolder
C:\Test\test\qwerty
C:\Test\test\test\qwerty
Run Code Online (Sandbox Code Playgroud)

剩下的就是:

C:\Test\
C:\Test\test\
C:\Test\test\test\
Run Code Online (Sandbox Code Playgroud)


Sta*_*kER 5

FOR /D /R %%X IN (fileprefix*) DO RD /S /Q "%%X"
Run Code Online (Sandbox Code Playgroud)

照顾好......

对于RD命令:

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.
/Q      Quiet mode, do not ask if ok to remove a directory tree with /S
Run Code Online (Sandbox Code Playgroud)

FOR命令用于循环遍历文件或变量列表,选项很容易记忆,目录只能递归.

  • @Achshar:基本上,把Y文件夹的名称改为`fileprefix`(`... IN(Y*)DO ...`).另外,将X文件夹的路径放在`/ R`和`%% X`之间(Jermaine错过了`/ R`开关需要一个参数,这是一个遍历的根文件夹).还有一件事,你还需要添加一个条件来确保你删除一个`Y`文件夹,而不是一个也匹配`Y*`掩码的`Ysomething`.这样的事情可能会:`......如果"%% ~nxX"=="Y"RD ......`. (2认同)