views:

328

answers:

3

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{"
A: 

Use RD C:\BLAH /S /Q command for Windows

Elalfer
A: 

There are two tools I can think of to check permission on the directory.

To remove readonly on the directories use

attrib -r /s <directory_name>

To view help on granting permissions on the directory

cacls /?
Jeremy E
A: 

The For /F line is the key. It takes the results of the part of the line in single quotes, and iterates over it.

So it takes a directory listing of the files in the target directory, excludes the first n lines based on the _NumtoKeep variable, and presents the results.

Then it asks a question with the Set _rdflag= /q line, confirming the action, before doing the work.

lavinio