删除根目录和子目录中的特定文件夹

删除根目录和子目录中的特定文件夹

我想删除根目录和子目录中的特定文件夹,问题是我的代码只删除目录根目录中的文件夹:

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

问题注释如下。主要问题是目录误解:您没有查看根目录下 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%
        )
    )

相关内容