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 :)
A problem common to this type of topics is that if there are instances of the target folder at several levels, most methods cause an error because when an high level folder is deleted, all folders below it disappear. For example:
Previous example generate a list of 4 folders named Y that will be deleted, but after the first one is deleted the three remaining names no longer exist, causing an error message when they are tried to delete. I understand this is a possibility in your case.
To solve this problem the folders must be deleted in bottom-up order, that is, the innermost folder must be deleted first and the top level folder must be deleted last. The way to achieve this is via a recursive subroutine:
Although in this particular case the problems caused by other methods are just multiple error messages, there are other cases when this processing order is fundamental.
Take care of using that...
for RD command:
the FOR command is used to loop through a list of files or variables, the options are very easy to memorize, Directory only Recursively.
Here is another solution for this commented to describe each part of the script:
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:You can also remove the
echo
in the loop portion and thepause
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
inC:\Test
:and all that was left was:
Make .bat with following: