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

后端 未结 4 580
忘了有多久
忘了有多久 2021-02-15 06:04

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

4条回答
  •  孤街浪徒
    2021-02-15 06:37

    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:

    C:\X\Y\subfolder
    C:\X\Y\subfolder\one\Y
    C:\X\Y\subfolder\two\Y
    C:\X\Y\subfolder\three\Y
    C:\X\test
    C:\X\test\test
    

    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:

    @echo off
    rem Enter into top level folder, process it and go back to original folder
    pushd x
    call :processFolder
    popd
    goto :EOF
    
    :processFolder
    rem For each folder in this level
    for /D %%a in (*) do (
       rem Enter into it, process it and go back to original
       cd %%a
       call :processFolder
       cd ..
       rem If is the target folder, delete it
       if /I "%%a" == "y" (
          rd /S /Q "%%a"
       )
    )
    exit /B
    

    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.

提交回复
热议问题