【问题标题】:How to delete a specific sub-folder in a parent folder using a batch file?如何使用批处理文件删除父文件夹中的特定子文件夹?
【发布时间】:2023-05-24 13:38:01
【问题描述】:

我想创建一个批处理文件来删除或删除文件夹C:\temp\root\students\type1、其子文件夹和所有文件。

我拥有的文件夹和文件如下:

C:\temp
C:\temp\root
C:\temp\root\students
C:\temp\root\tutors
C:\temp\root\students\type1
C:\temp\root\students\type2
C:\temp\root\tutors\type1
C:\temp\root\tutors\type2
C:\temp\root\students\type1\details.txt
C:\temp\root\students\type1\assignment1
C:\temp\root\students\type1\assignment1\results.txt

文件夹C:\temp\root\students\type1\assignment1 在批处理文件中指定。

我想上一个文件夹/目录并删除或删除我的批处理文件 (test.bat) 中的 C:\temp\root\students\type1

请帮帮我。

【问题讨论】:

  • C 是一种编程语言,而不是任何硬盘驱动器。这不应该被标记为 C。
  • 您现有的批处理文件命令在哪里?只需更改文件夹以符合您的需要

标签: windows batch-file cmd


【解决方案1】:

使用这个:

rd /s /q C:\temp\root\students\type1

它会递归删除文件和文件夹,小心,没有提示。它是旧的 deltree 的替代品。最好的。

编辑:在您的记事本中,使用以下内容创建您的 mygoodbatch.bat

md C:\temp
md C:\temp\root
md C:\temp\root\students
md C:\temp\root\tutors
md C:\temp\root\students\type1
md C:\temp\root\students\type2
md C:\temp\root\tutors\type1
md C:\temp\root\tutors\type2
md C:\temp\root\students\type1\details.txt
md C:\temp\root\students\type1\assignment1
md C:\temp\root\students\type1\assignment1\results.txt
rd /s /q C:\temp\root\students\type1

mdma​​ke dir dos 命令,所以以它开头的所有行都在创建文件夹 - 最后一行是删除您的 4AA 级别的行)

将此批处理保存在磁盘的根目录中,然后运行它。我真的希望这是你想要的。我还没有理解的是:你在创建一个目录结构,同时排除4AA级……是这样吗?

【讨论】:

  • 非常感谢您的回复。这些是物理文件夹/目录。有没有办法从批处理文件中检索此文件夹结构并删除此特定文件夹?我所说的文件夹结构的意思是: C:\temp is Level 1 C:\temp\root is Level 2 C:\temp\root\students 是 3A 级 C:\temp\root\tutors 是 3B 级 C:\temp\root\students\type1 是 4AA 级 C: \temp\root\students\type2 是 4AB 级 C:\temp\root\tutors\type1 是 4BA C:\temp\root\tutors\type2 是 4BB
  • 抱歉,不确定我是否理解正确。主要原则是:从我上面的回答中,您放置在 C:\temp\root\students\type1 的任何内容,此文件夹中的任何内容都将被删除。
  • 在我的批处理文件中,我想按照下面提到的按级别创建此文件夹结构,并删除引用 4AA 级别的文件夹。我是新手,所以我的批处理文件中还没有任何内容。感谢您的时间和帮助。
  • 已编辑。我越来越糊涂了。到目前为止,您还没有提到创建文件夹,只是不包括...:P 希望我能帮上忙。
【解决方案2】:

您可以使用 for 循环来获取给定文件夹的父文件夹:

set target_dir=C:\temp\root\students\type1.test\assignment1

for %%a in ("%target_dir%") do (
    echo Removing %%~dpa%
    rd /s/q %%~dpa%
)

【讨论】: