刪除根目錄和子目錄中的特定資料夾

刪除根目錄和子目錄中的特定資料夾

我想刪除根目錄和子目錄中的特定資料夾,問題是我的程式碼僅刪除目錄根目錄中的資料夾:

SET dirname=test
SET directory=%cd%
SET found=false


    if NOT "%1%" == "" (
        set directory=%1%
    )
    echo Searching for %dirname% in %directory%

    for /d %%i in (%directory%\%dirname%) do (
        IF EXIST %%i (
            REM change the sentinel value
            set found=true

            echo Deleting the folder %%i
            REM Delete a folder, even if not empty, and don't prompt for confirmation
            RD  /s /q %%i
        )
    )

    REM logic to do if no files were found
    if NOT "%found%" == "true" (
        echo No directories were found with the name of %dirname%
    )

這是資料夾結構:

E:sampledelete
├───folder1
├───folder2
│   └───somefolder
├───test
│   └───somefolder
├───newfolder
│   ├───test
│   │   └───somefolder
├───newfolder2
│   ├───test

運行腳本後它更改為:

E:sampledelete
├───folder1
├───folder2
│   └───somefolder
├───newfolder
│   ├───test
│   │   └───somefolder
├───newfolder2
│   ├───test

答案1

這些問題註記如下。主要問題是目錄誤解:您沒有查看 root 下 1 個節點下的目錄。你的想法是正確的。正如您所說,由於您是“新人”,因此值得分析差異。

@echo off
SET dirname=test
SET directory=%cd%
SET found=false

    if NOT "%1%" == "" (
        set directory=%1%
    )

    REM We want to look in the current directory not in for Z:\test
    for /d %%i in (%directory%*) do (
        echo Searching for %%i\%dirname% in %directory%

        REM We already know the folder existed because "do" ran.
        REM We want to look beneath the root directory
        IF EXIST %%i\%dirname% (
            REM change the sentinel value
            set found=true

            REM we want to delete the nodes beneath not the one in root
            echo Deleting the folder %%i\%dirname%

            REM Delete a folder
            REM we want to delete the nodes beneath not the one in root
            RD  /s /q %%i\%dirname%
        )

        IF %%1 == %dirname% (
            REM change the sentinel value
            set found=true

            REM Delete a folder, even if not empty, and don't prompt for confirmation
            echo Deleting the folder %%i\%dirname%
            RD  /s /q %%i
        )
    )

    REM logic to do if no files were found
    if NOT "%found%" == "true" (
        echo No directories were found with the name of %dirname%
    )

答案2

你誤解了它for /d的作用。

對於 /d %%i (目錄1文件1目錄2文件2目錄3文件3) 做陳述

  • SET %%i=dir1
  • statement
  • SET %%i=dir2
  • statement
  • SET %%i=dir3
  • statement

問題是,你只是說 ,在哪裡。您想要使用,它會進行遞歸目錄搜尋。你的循環應該看起來像for /d %%i in (dir1) do statementdir1
%directory%\%dirname%for /r

    for /r %directory% %%i in (.) do (
        if exist %%i\%dirname% (
            REM change the sentinel value
            set found=true

            echo Deleting the folder %%i\%dirname%
            REM Delete a folder, even if not empty, and don't prompt for confirmation
            RD  /s /q %%i\%dirname%
        )
    )

相關內容