Aaron Brewer
Aaron Brewer

Reputation: 3667

Remove All Sub-Directories and Sub-Files Without Removing Parent/Root Directory?

Via Windows Batch, what would the command be to remove all sub directories and sub files of a folder without deleting/removing the said parent/root folder?

Here's what I have tried so far:

ECHO "Good riddance, cache! Muahahahahahaha"
cd "C:\Users\abrewer\Desktop\cache"
del * /q

The above only removes files, but not sub folders. I have also tried RMDIR and RD, those two commands seem to remove the parent/root directory.

Upvotes: 3

Views: 12036

Answers (3)

M Smith
M Smith

Reputation: 78

cd "C:\Users\abrewer\Desktop\cache"
if %errorlevel% neq 0 exit /b %errorlevel%
rd /s /q .

The first part of the top answer is great but it's also dangerous. Please make sure you have some error checking in your code, as if the directory doesn't exist for some reason you're going to delete what's in your working path.

I'm too new to add a comment and the edit queue was full for the answer to suggest an amendment.

Upvotes: 0

dbenham
dbenham

Reputation: 130819

@echo off
ECHO "Good riddance, cache! Muahahahahahaha"
pushd "C:\Users\abrewer\Desktop\cache"
del * /q
for /d %%F in (*) do rd /s /q "%%F"
popd

Upvotes: 3

Harry Johnston
Harry Johnston

Reputation: 36308

The simplest way of doing it:

cd "C:\Users\abrewer\Desktop\cache"
rd /s /q .

It outputs an error message when it tries and fails to delete the parent directory, but otherwise it works perfectly.

Alternatively, something like:

cd "C:\Users\abrewer\Desktop\cache"
del * /q
for /D %%i in (*) do rd /s /q "%%i"

might work. Remember to only use single percent signs if you're running from the command line rather than in a batch file.

Upvotes: 6

Related Questions