Submitted By: David Fox

Purges old files from a specified folder based upon the modification date of those files. All files older than a specified number of days will be deleted.

Visual Basic
Edit|Remove
'
'  PurgeFiles.vbs
' --------------------
'   Delete certain files based upon their last modif. date
'   Parameters:
'        1 - folder path where file(s) are to be purged
'        2 - # of days to retain logfiles
'
'   CSCRIPT PurgeFiles.vbs  "c:\xyz\logs\"    7
'
OPTION Explicit

  Dim   f, fso, oFolder, oFileList
  Dim   Keep_Days, Purge_Date, CmdArg_Object, sFolderPath, lastModDate
'---------------------------------------------------------------------------
'
'  Were any parameters passed in?
'
Set CmdArg_Object = Wscript.Arguments

Select Case (CmdArg_Object.Count)
    Case 2
      sFolderPath = CmdArg_Object.item(0)
      Keep_Days = CmdArg_Object.item(1)
    Case Else
      WScript.Echo "PurgeFiles.vbs requires 2 parameters:" &_
        vbcrlf & "1) Folder Path" &_
        vbcrlf & "2) # Days to Retain"
      WScript.Quit
End Select

'
'  Loop thru all files meeting this filespec
'  For each one, delete it if it's mod. date is older than Keep_Days
'
Set fso = CreateObject("Scripting.FileSystemObject")
Purge_Date = Date+(-1*Keep_Days)

WScript.Echo "***" & Now & " - Beginning " & Keep_Days & " day purge of " & sFolderPath
Set oFolder = fso.GetFolder(sFolderPath)
Set oFileList = oFolder.Files
For Each f in oFileList
    lastModDate = f.DateLastModified
    If (lastModDate <= Purge_Date) Then
        WScript.Echo "Deleting " & f.Name & " /modified=" & f.DateLastModified & vbcrlf
        f.Delete true
    End If
Next

WScript.Echo "***" & Now & " - Finished"