Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: Keep latest subfolders  (Read 7178 times)

0 Members and 1 Guest are viewing this topic.

Hu

    Topic Starter


    Rookie
    Keep latest subfolders
    « on: February 13, 2006, 07:54:34 AM »
    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.







    Sidewinder



      Guru

      Thanked: 139
    • Experience: Familiar
    • OS: Windows 10
    Re:  Keep latest subfolders
    « Reply #1 on: February 13, 2006, 06:33:02 PM »
    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-)

    The true sign of intelligence is not knowledge but imagination.

    -- Albert Einstein