开发者

Delete contents of a directory recursively on Windows

I need to delete the entire contents of a directo开发者_如何学Pythonry (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:

rm -rf *

What is the Windows equivalent?


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 *


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.

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.

echo %errorlevel%
0

It's what I'm using and it works fine. I hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜