How to remove all folders of name x within a directory using cmd/batch file

batch-file, cmd

Solution

Here is another solution for this commented to describe each part of the script:

@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

You can take the `/p` out from in front of the initial variables and just enter their values after the `=` if you don't want to be prompted:

set foldername=
set root=

You can also remove the `echo` in the loop portion and the `pause` in the end portion for the batch to run silently.

It might be a little more complicated, but the code can be applied to a lot of other uses.

I tested it looking for multiple instances of the same foldername `qwerty` in `C:\Test`:

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

and all that was left was:

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

Problem

I have a folder named x with a number of subfolders and files. I want to delete a folder named y that is present in x and all of it's subfolders. The said folder that has to be deleted may or may not contain any files. I believe i can do this using cmd or some kind of batch file but i am a command line new bi and can really use some help. A simple thing would be to rd the folder's name, which works but i believe there are better ways than removing each folder individually.. like some loop that goes through all the folders. Thanks EDIT: Just to clarify, i have y (the folder that needs to be deleted) inside of x, and it can be in any of x's subfolders and at any level of depth. Also i am looking at answers and it may take some time for me to accept any answer. Please bear with me :)

Original source