删除多个目录的内容(仅当它们存在时)(批处理文件)

时间:2017-01-02 13:38:31

标签: windows batch-file

我正在尝试编写一个可以清理磁盘空间的简单批处理文件。我必须删除4个不同目录的全部内容(文件夹和文件),但前提是它们存在。我一直在测试尝试删除一个,但我对编写批处理文件一无所知。经过我所做的所有研究后,我想出了几行无效的代码。

@echo off
IF EXIST "C:\Windows\TestFolder\TestSubFolder\*.*"
DEL /s /q "C:\Windows\TestFolder\TestSubFolder\*.*"
for /d %%p in ("C:\Windows\TestFolder\TestSubFolder\*.*") do rmdir "%%p" /s /q
exit

在这种情况下,如果TestSubFolder存在,我需要能够删除TestSubFolder的内容。无论是否存在,在该操作完成后,我需要代码对TestSubFolder2执行相同的操作。

由于

2 个答案:

答案 0 :(得分:1)

代码中的主要问题是if命令的使用不当。如果条件为真,则只有一个命令可以执行,它可以写在同一行,但要在下一行写入命令,则需要使用括号。它应该像

IF EXIST "C:\Windows\TestFolder\TestSubFolder\*.*" (
    DEL /s /q "C:\Windows\TestFolder\TestSubFolder\*.*"
    for /d %%p in ("C:\Windows\TestFolder\TestSubFolder\*.*") do rmdir "%%p" /s /q
)

但这可以简化为

2>nul pushd "C:\Windows\TestFolder\TestSubFolder" && (
    rmdir . /s /q
    popd
)

也就是说,我们尝试更改为指定的文件夹(pushd)并且如果没有任何问题(条件执行操作符&&表示如果前一个命令没有失败则执行下一个命令)删除文件夹的所有内容(rmdir)并返回上一个活动目录(popd)。 2>nul只是隐藏任何错误消息(例如文件夹不存在,锁定的文件无法删除,...)

现在,如果必须为多个文件夹重复该过程,我们可以使用for命令迭代文件夹列表

for %%a in ( "folder1" "folder2" ) do ....

将之前的代码放入此for循环中

@echo off
    setlocal enableextensions disabledelayedexpansion

    2>nul (
        for %%a in (
            "C:\Windows\TestFolder\TestSubFolder"
            "C:\Windows\TestFolder\TestSubFolder2"
        ) do pushd "%%~fa" && ( 
            rmdir . /s /q 
            popd 
        )
    )

错误隐藏已移至涵盖所有for执行,现在,对于每个文件夹(由for可替换参数%%a引用),我们尝试更改使用完整路径(%%~fa)到文件夹,如果我们可以更改它,然后删除所有文件夹内容,然后返回到原始活动目录。

答案 1 :(得分:0)

CD "C:\Windows\TestFolder\TestSubFolder"
RD /s /q  "C:\Windows\TestFolder\TestSubFolder"

适合我。

或从任何地方

RD /s /q  "C:\Windows\TestFolder\TestSubFolder"
MD "C:\Windows\TestFolder\TestSubFolder"