简体   繁体   中英

Delete contents of a directory recursively on Windows

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM