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?
The command DEL is used to delete all files in the specified directory. The option /A is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A . The option /F is necessary to force deletion of files with the read-only attribute set.
To delete files or folders recursively, you can utilize Windows Command Prompt or Windows PowerShell. In the Command Prompt, use “rmdir” or “rd” commands with the “/s” option is used to remove folders recursively.
In the Windows Command Prompt, we can replace the “rm” command with the “rd” command and the “f” option with “/s” to delete files and folders forcefully.
On Windows 10, you can use Command Prompt and Task Scheduler to automatically delete files older than a certain number of days to free up space and keep your files organized. The Settings app includes Storage sense, a feature that automatically runs when the storage is low in space.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With