Script to delete files older than x days

A quick script to delete files older than a certain number of days, be careful if you run this against a root dir!


'*  Script Name:        DeleteOldFiles.vbs
'*  Created On:         08/08/2013
'*  Author:                Jimmy White
'*  Version:            1.0
'NOTE! The Account used to run script needs delete permissions to folder & files.
Const sSource    = "G:\" ' For example, or "X:\" but not "G:"
Const MaxAge     = 30 'time in days
Const Recursive  = True 'deletes everything under the source
Dim dtOld, Checked, Deleted, verb
dtOld   = Now - MaxAge
Checked = 0
Deleted = 0
Validate sSource
Cleanup sSource
Sub Validate(sFolder)
    With CreateObject("Scripting.FileSystemObject")
        If Not .FolderExists(sFolder) Then
            Err.Raise 76 'Path not found
        End If
        If .GetFolder(sFolder).IsRootFolder Then
            If .GetDrive(.GetDriveName(sFolder)) = _
            "PROCESS")("HOMEDRIVE") Then
                Err.Raise 75 'Path/File access error
            End If
        End If
    End With
End Sub
Sub Cleanup(sFolder)
    On Error Resume Next
    Dim obj
    With CreateObject("Scripting.FileSystemObject").GetFolder(sFolder)
        'recurse first
        If Recursive Then
            For Each obj In .SubFolders
                Cleanup obj
        End If
        'next delete oldest files
        For Each obj In .Files
            If obj.DateCreated < dtOld Then
                Deleted = Deleted + 1
                WScript.Echo verb & obj.Path & """"
                If Active Then obj.Delete(True)
            End If
        Checked = Checked + .Files.Count
        'and then delete old or empty folders
        For Each obj In .SubFolders
            If obj.DateCreated < dtOld Or 0 = obj.Size Then
                'count here in a variable if you like...
                If Active Then obj.Delete(True)
If Err.Number<>0 THen
                            'do nothing!
                  End If
            End If
    End With
End Sub



Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.