1.

Solve : Keep latest subfolders?

Answer»

The following vb script delete a folder:
SET fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFolder "C:\myfolder",false
Set fso = Nothing

If I have subfolders by date like:
C:\myfolder\Oct 12
C:\myfolder\Oct 15
C:\myfolder\Nov 30
C:\myfolder\DEC 21
how do I keep the latest 2 subfolders and delete the rest?

Thanks for the input.






Naming your folders with literal months makes things difficult. Consider that FEB, Apr, Aug, and Dec will all sort before Jan. Presumably not what you want.

With script of course you have other options.

Code: [Select]Dim arrdsn()
Dim arrdate()
Const fld = "c:\My Folder"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(fld)
Set fc = f.Subfolders

For Each fs in fc
      ReDim Preserve arrdsn(i)
      ReDim Preserve arrdate(i)
      arrdsn(i) = fs.name
      arrdate(i) = fs.DateCreated
      i = i + 1
Next

For i = UBound(arrDate) - 1 To 0 Step -1
       For j = 0 to i
        If arrDate(j) < arrDate(j+1) then
           tmpDate = arrDate(j+1)
           tmpDsn = arrDsn(j+1)
           arrDate(j+1) = arrDate(j)
           arrDsn(j+1) = arrDsn(j)
           arrDate(j) = tmpDate
           arrDsn(j) = tmpDsn
         End if
       Next
Next

For i = 2 to UBound(arrdsn)
      fso.DeleteFolder fld & "\" & arrdsn(i), True
Next

You may want to substitute a WScript.Echo in place of the fso.DeleteFolder statement to get an idea of what will be deleted before going live with this.

Good LUCK. 8-)



Discussion

No Comment Found