3

I would like the functionality of rmdir /s but I need to keep the specified directory. rmdir /s removes all files and sub directories in addition to the directory specified.

I've also tried using del /s but then I am left with empty folders in the specified directory. I need those folders removed as well.

Any guidance on how I can do this?

Justin Self
  • 6,137
  • 3
  • 33
  • 48

2 Answers2

7

Easiest way would be to change directory to specified directory and invoke an rd command on the "." directory. Like:

cd toYourDirectory (or pushd toYourDirectory)
rd /q /s . 2> nul
  • /q - ensures you wont be prompted
  • /s - to do subfolders, files, so on..
  • the "." - implies CURRENT directory
  • 2>nul - ensures it won't report the error when the rd command attempts to remove itself (which is what you want)
Arun
  • 2,493
  • 15
  • 12
1

<3 for loops

FOR /F "USEBACKQ tokens=*" %%F IN (`dir /b /a:d /s "C:\top\directory\" ^| FIND /v /i "C:\directory\to\omit"`) DO (
 rmdir /s "%%F"
)

and if you wish to strike dangerously, use the /q switch w/ rmdir 0.o

So lets say, you want to perform a remdir /s on C:\Documents and Settings\Mechaflash\, HOWEVER you wish to keep the .\Mechaflash folder (emptied)

FOR /F "USEBACKQ tokens=*" %%F IN (`dir /b /a:d /s "C:\Documents and Settings\Mechaflash\" ^| FIND /v /i "C:\Documents and Settings\Mechaflash\"`) DO (
 rmdir /s "%%F"
)
DEL /Q /F "C:\Documents and Settings\Mechaflash\*"
Anthony Miller
  • 15,101
  • 28
  • 69
  • 98
  • I really appreciate the answer; however, if I'm going to make two statements, I might as well use rmdir and mkdir. – Justin Self Aug 31 '11 at 18:42
  • Yeah... that for loop is way overkill LOL. rmdir and mkdir is the same exact effect. Now unless the folder in question has system/hidden files you would like to keep, then rmdir on the folder may not be ideal – Anthony Miller Aug 31 '11 at 18:53
  • You should never iterate over `dir` output in this way unless absolutely necessary. There are severe drawbacks regarding Unicode file names that are not present when iterating directly with `for`. In this case you could simply use a normal `for` loop with a conditional inside. Although I don't quite understand where you get the need to omit a directory anyway. – Joey Sep 01 '11 at 19:01
  • Using rmdir and mkdir will lose any special permissions (ACLs) on the directory. – Richard A Sep 08 '11 at 01:11