问题
I have a directory as such:
D:\Movies
D:\Movies\MovieTitle1\backdrops\
D:\Movies\MovieTitle2\backdrops\
D:\Movies\MovieTitle3\backdrops\
D:\Movies\MovieTitle4\backdrops\
How could I have a batch file delete all folders named "Backdrops"? I would prefer it to run recursive from just the D:\ drive if possible.
回答1:
Short answer:
FOR /d /r . %d IN (backdrops) DO @IF EXIST "%d" rd /s /q "%d"
I got my answer from one of the countless answers to the same question on Stack Overflow:
Command line tool to delete folder with a specified name recursively in Windows?
This command is not tested, but I do trust this site enough to post this answer.
As suggested by Alex in a comment, this batch script should be foolproof:
D:
FOR /d /r . %d IN (backdrops) DO @IF EXIST "%d" rd /s /q "%d"
回答2:
Above answer didn't quite work for me. I had to use a combination of @itd solution and @Groo comment. Kudos to them.
Final solution for me was (using the backdrop folder example):
FOR /d /r . %%d IN ("backdrops") DO @IF EXIST "%%d" rd /s /q "%%d"
回答3:
I will open a different answer, because it would be too cramped in the comments. It was asked what to do, if you want to execute from/to a different folder and I want to give an example for non-recursive deletion.
First of all, when you use the command in cmd, you have to use %d
, but when you use it in a .bat, you have to use %%d
.
You can use a wildcard to just process folders that for example start with "backdrops": "backdrops*"
.
Recursive deletion of folders starting in the folder the .bat is in:
FOR /d /r . %d IN ("backdrops") DO @IF EXIST "%d" rd /s /q "%d"
Non-recursive deletion of folders in the folder the .bat is in (used with wildcard, as you cannot have more than one folder with the same name anyway):
FOR /d %d IN ("backdrops*") DO @IF EXIST "%d" rd /s /q "%d"
Recursive deletion of folders starting in the folder of your choice:
FOR /d /r "PATH_TO_FOLDER" %d IN ("backdrops") DO @IF EXIST "%d" rd /s /q "%d"
Non-recursive deletion of folders in the folder of your choice (used with wildcard, as you cannot have more than one folder with the same name anyway):
FOR /d %d IN ("PATH_TO_FOLDER/backdrops*") DO @IF EXIST "%d" rd /s /q "%d"
来源:https://stackoverflow.com/questions/25554254/batch-command-to-delete-all-subfolders-with-a-specific-name