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

后端 未结 4 577
忘了有多久
忘了有多久 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:28

    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\
    

提交回复
热议问题