Delete all subdirectories & files under a directory

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
tinfanide
Posts: 117
Joined: 05 Sep 2011 09:15

Delete all subdirectories & files under a directory

#1 Post by tinfanide » 28 Sep 2011 07:55

How can I delete all subdirectories & files under a directory without deleting the directory itself?

Cache\
Folder1
File1.txt
File2.txt
File3.txt

Code: Select all

RD "\My Software\FirefoxPortable+TorPortable\FirefoxPortable\Data\profile\Cache\" /s


My code above deletes all the folders and files including the directory itself.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Delete all subdirectories & files under a directory

#2 Post by dbenham » 28 Sep 2011 08:23

untested batch script:

Code: Select all

@echo off
setlocal
set "myPath=\My Software\FirefoxPortable+TorPortable\FirefoxPortable\Data\profile\Cache\"
for /d %%d in ("%myPath%*") do rd /s /q "%%~fd"
del /q "%myPath%*


Dave Benham

tinfanide
Posts: 117
Joined: 05 Sep 2011 09:15

Re: Delete all subdirectories & files under a directory

#3 Post by tinfanide » 28 Sep 2011 18:27

Amazing...
Ya script does work.

Could ya explain a bit the use of "%%~fd",
why we need * after %myPath%?
Why it is

"%myPath%*
not
"%myPath%"

I can hardly find it online for explanation.

And,
while I was reading ya script, I was trying another way...

Code: Select all

@echo off

set delContent="o:\d"

del %delContent% /q
for /f "Tokens=*" %%G in ('dir "%delContent%" /ad /s /B') do rd /s /q "%%G"

exit

The only thing that goes wrong is that every time it deletes a subfolder or a file, it echoes "cannot find the specified path" or something like that
Last edited by tinfanide on 28 Sep 2011 18:46, edited 1 time in total.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Delete all subdirectories & files under a directory

#4 Post by dbenham » 28 Sep 2011 18:43

tinfanide wrote:Could ya explain a bit the use of "%%~fd"?
I can hardly find it online for explanation.

%%d is simply the FOR variable and ~f is a modifier that causes the variable to be expanded to the full path of the file. I'm not sure the ~f modifier is needed in this case, but it can't hurt.

Type HELP FOR to get help on the FOR command, including a description of all of the modifiers at the bottom of the listing

Dave Benham

tinfanide
Posts: 117
Joined: 05 Sep 2011 09:15

Re: Delete all subdirectories & files under a directory

#5 Post by tinfanide » 28 Sep 2011 19:14

Yes, I see. Thank you.

Post Reply