Batch File to Delete Folders
Posted
by Homebrew
on Stack Overflow
See other posts from Stack Overflow
or by Homebrew
Published on 2009-11-20T21:49:12Z
Indexed on
2010/03/23
22:53 UTC
Read the original article
Hit count: 250
I found some code to delete folders, in this case deleting all but 'n' # of folders. I created 10 test folders, plus 1 that was already there. I want to delete all but 4. The code works, it leaves 4 of my test folders, except that it also leaves the other folder. Is there some attribute of the other folder that's getting checked in the batch file that's stopping it from getting deleted ? It was created through a job a couple of weeks ago.
Here's the code I stole (but don't really understand the details):
rem DOS - Delete Folders if # folders > n
@Echo Off
:: User Variables
:: Set this to the number of folders you want to keep
Set _NumtoKeep=4
:: Set this to the folder that contains the folders to check and delete
Set _Path=C:\MyFolder_Temp\FolderTest
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
PushD %_Path%
Set _s=%_NumtoKeep%
If %_NumtoKeep%==1 set _s=single
For /F "tokens=* skip=%_NumtoKeep%" %%I In ('dir "%_Path%" /AD /B /O-D /TW') Do (
If Exist "%temp%\tf}1{" (
Echo %%I:%%~fI >>"%temp%\tf}1{"
) Else (
Echo.>"%temp%\tf}1{"
Echo Do you wish to delete the following folders?>>"%temp%\tf}1{"
Echo Date Name>>"%temp%\tf}1{"
Echo %%I:%%~fI >>"%temp%\tf}1{"
))
PopD
If Not Exist "%temp%\tf}1{" Echo No Folders Found to delete & Goto _Done
Type "%temp%\tf}1{" | More
Set _rdflag= /q
Goto _Removeold
Set _rdflag=
:_Removeold
For /F "tokens=1* skip=3 Delims=:" %%I In ('type "%temp%\tf}1{"') Do (
If "%_rdflag%"=="" Echo Deleting
rd /s%_rdflag% "%%J")
:_Done
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
© Stack Overflow or respective owner