简体   繁体   中英

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.

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.

@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
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.

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