Link to home
Start Free TrialLog in
Avatar of adiemeer
adiemeer

asked on

CMD command to remove subdirectories and files from a certain folder

Hello,

I want to use the command prompt to empty all the files and subdirectory of a certain directory. For example the directory C:\test. Important is that I don't want to delete the C:\test, only the files and subdirectories in this folder. I tried the command:

del C:\test /q /s

But this command doesn't delete the subdirectories. The /q is important as I don't want to confirm that I really want to delete the files and subdirectories. Anyone idea how to solve this?

Regards Arne
Avatar of oBdA
oBdA

If you want to keep the root folder, you need two steps: delete all files in the folder, and delete all subfolders of the folder.
Handle with care.
@echo off
setlocal
set Root=C:\Test
if not exist "%Root%" (
	echo Root folder '%Root%' not found.
	exit /b 1
)
del "%Root%\*.*" /f /q
for /d %%a in ("%Root%\*.*") do (
	rd /s /q "%%a"
)

Open in new window

First point - why does this have to be ONE command?

Second point - why not just delete test completely and then recreate it a moment later?

RD /q /s c:\test & md c:\test

Alternatively:
del c:\test\*.* /q & for /f %a in ('dir c:\test /ad /b') do rd /s /q c:\test\%a

I assume you're NOT putting this in a batch file - if you are, one of the above won't work without modification.
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks oBdA, good points.

So I guess I'll propose these three approaches built off of the CD trick I started from.  But certainly brute force without the PUSHD/POPD works great too, just a bit more code.  But maybe wrap it in a funtion if needed often.

rem Inline, verbose method
set DirName=c:\temp
pushd "%DirName%" && (
  rd /q /s "%DirName%" 2>NUL
  popd
)


rem Inline, compact method
pushd "c:\temp" && (rd /q /s "c:\temp" 2>NUL & popd)


rem Function call
call :PurgeDir "c:\temp"
exit /b

:PurgeDir [directory-path]
  pushd "%~1" && (
    rd /q /s "%~1" 2>NUL
    popd
  )
  exit /b

Open in new window

~bp
Avatar of adiemeer

ASKER

Thanks!
Based on last experts feedback exchange between Bill Prew and oBdA the assisted solution should be the last comment of Bill Prew and not the one reported previously. Can someone repopen the question and assign the right assisted solution. This will allows us to add the right solution to our personal Knowledge base.
Thank you very much for your help.