在 Windows 上递归删除目录的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5108490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete contents of a directory recursively on Windows
提问by Konstantin Komissarchik
I need to delete the entire contents of a directory (nested folders and all) without deleting the directory itself. Recreating the directory after the fact is not an option as it is being locked by the running process and delete of it would fail.
我需要删除目录的全部内容(嵌套文件夹和所有内容)而不删除目录本身。事后重新创建目录不是一个选项,因为它被正在运行的进程锁定并且删除它会失败。
So far I have the following:
到目前为止,我有以下几点:
rd /s /q dir1
rd /s /q dir2
rd /s /q dir3
del /q /f *
It works, but the obvious problem is that I have to update this script every time the set of first-level directories changes.
它有效,但明显的问题是每次第一级目录集更改时我都必须更新此脚本。
On UNIX, I would solve this like this:
在 UNIX 上,我会这样解决这个问题:
rm -rf *
What is the Windows equivalent?
什么是 Windows 等价物?
回答by Ben Hoffstein
Assuming that you are executing the command from the top-level directory:
假设您正在从顶级目录执行命令:
for /d %X in (*.*) do rd /s /q %X
If you are executing this from a script, you must use double percent signs:
如果您从脚本执行此操作,则必须使用双百分号:
for /d %%X in (*.*) do rd /s /q %%X
If you need to delete the files in the top-level directory as well, add this to the script:
如果您还需要删除顶级目录中的文件,请将其添加到脚本中:
del /q /f *
回答by Mig82
I know this is an old question with an old answer, but I've found a simpler way to do this and thought of sharing it.
我知道这是一个有旧答案的老问题,但我找到了一种更简单的方法来做到这一点并考虑分享它。
You can step into the target directory and use the rd
command. Since Windows will not allow you to delete any files or directories currently in use, and you are making use of the target directory by stepping into it, you'll delete all the contents, except the target directory itself.
您可以进入目标目录并使用该rd
命令。由于 Windows 不允许您删除当前正在使用的任何文件或目录,并且您正在通过单步进入目标目录来使用它,因此您将删除除目标目录本身之外的所有内容。
cd mydir
rd /s /q .
You'll get a message saying:
你会收到一条消息:
The process cannot access the file because it is being used by another process.
该进程无法访问该文件,因为它正被另一个进程使用。
This will occur when, after deleting all the contents, the rd
command fails to delete the current directory, because you're standing in it. But you'll see this is not an actual error if you echo the last exit code, which will be 0
.
当删除所有内容后,该rd
命令无法删除当前目录时,就会发生这种情况,因为您正站在其中。但是,如果您回显最后一个退出代码(即0
.
echo %errorlevel%
0
It's what I'm using and it works fine. I hope this helps.
这是我正在使用的,并且工作正常。我希望这有帮助。