Page 1 of 1

Delete all subdirectories & files under a directory

Posted: 28 Sep 2011 07:55
by tinfanide
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.

Re: Delete all subdirectories & files under a directory

Posted: 28 Sep 2011 08:23
by dbenham
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

Re: Delete all subdirectories & files under a directory

Posted: 28 Sep 2011 18:27
by tinfanide
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

Re: Delete all subdirectories & files under a directory

Posted: 28 Sep 2011 18:43
by dbenham
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

Re: Delete all subdirectories & files under a directory

Posted: 28 Sep 2011 19:14
by tinfanide
Yes, I see. Thank you.