Viki2016
Viki2016

Reputation: 55

Delete everything from Subfolders through Batch file

I have directories like:

c:\Project\Current\stage1\somefiles and some folders
c:\Project\Current\stage2\somefiles and some folders
c:\Project\Current\stage3\somefiles and some folders
c:\Project\Current\stage4\somefiles and some folders
c:\Project\Current\stage5\somefiles and some folders
.
.
.
c:\Project\Current\stage500\somefiles and some folders

I want to create a batch file so that everything inside stage1, stage2,..., stage500 will get deleted but not any of other folders so that I can still see the above directories but empty.

Can someone please help?

Upvotes: 0

Views: 79

Answers (2)

Viki2016
Viki2016

Reputation: 55

I found the answer and is very simple

for /d %%X in (c:\Project\Current*) Do (
for /D %%I in ("%%X\*") do rmdir /s/q "%%I"
del /F /q "%%X\*")

Thanks for everyone's help..

Upvotes: 1

MichaelS
MichaelS

Reputation: 6042

Try this:

@echo off
CD c:\Project\Current /d
for /f "tokens=*" %%f in ('dir /a-d /s /b') do (
    del "%%f" /q /f
)

There are three important parts:

for /f "tokens=*" %%f means we are iterating over all lines that are generated by the following command and temporarily save each line in the variable %%f for each iteration.

dir /a-d /s /b is the core of the code. This will list all files inside c:\Project\Current\ including all subfolders. /a-d means that directories will be ignored as we don't want them to be erased. /s means we are searching any subfolder. /b sets the output format to simple mode so that each line of the output will contain nothing but the full path to a file.

del "%%f" /q /f simply deletes the file which is stored in %%f. /q means "don't ask me if I'm sure, just erase it" and /f means that any file - even if it is marked as system file or as invisible or protected - will be deleted. Don't miss the quotation marks around %%f as otherwise paths containing spaces will cause trouble.

Upvotes: 1

Related Questions