Search code examples
batch-filecommand-linevbscriptdelete-filedir

Recursively search sub-folders and delete all files in sub-folders older than 6-months


We have a directory structure like this

..\Document Name_archive\YYYY\MonthName

so for example we have many sub-folders (within different document name folders) called \2014\January ... etc

We'd like to remove all the folders and their contents that have a created date older than 180 days.

We'd prefer to just use a batch file script, but perhaps a VBScript is better if we need to recursively search.

What's the best way please?


Solution

  • Here's a VBScript solution that uses a recursive function.

    ' Global FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    
    ' Start at the root
    DoFolder "c:\document_root\"
    
    ' Recursive function
    Sub DoFolder(strFolder)
    
        With objFSO.GetFolder(strFolder)
    
            For Each objFile In .Files
                If objFile.DateCreated < Date - 180 Then objFile.Delete
            Next
    
            For Each objFolder In .SubFolders
                DoFolder objFolder.Path
            Next
    
            ' Checked every file and subfolder. If this folder is empty, remove it...
            If .Files.Count = 0 Then If .SubFolders.Count = 0 Then .Delete
    
        End With
    
    End Sub
    

    See this post for a batch example using the forfiles command.