Friday, July 20, 2012

VB Script to Delete Files by Date


So I wanted to test out this new plugin I just download for Live Writer (I know, I know… I promise I'm not giving in to Microsoft) that displays code snippets with formatting and color-highlighting…
So here is a visual basic script I had to write the other day that reads in two string variables “strDir” and “strDays” (definitions below) and deletes files with certain file extensions... 

strDir = The directory that you want files deleted from
strDays = The number of days from previous day that you want deleted


' =======================================================================
PURPOSE: Cleanup Script for //Your/Dir/. Script will delete files older than strDays 

                        with a file extension of XLS or DOC
AUTHOR: Robert Lacy
DATE: 1/30/2012
' =======================================================================
Dim fso, f, f1, fc, strComments
strDir = "C:\Your\Dir\"
strDays = 7

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(strDir)
Set fc = f.Files
' === Comment out the below IF statement if you need to run this script in the background
If fc.Count = 0 Then
     WScript.echo "No Files Exist in Target Directory = " & strDir
     WScript.Quit
End If
' === If Files Exists, try to Delete them...
For Each f1 in fc
     If DateDiff("d", f1.DateCreated, Date) >= strDays and (fso.GetExtensionName(UCase(f1.name)) ="XLS" or fso.GetExtensionName(UCase(f1.name)) = "DOC") Then
          strComments = strComments & "Deleted: " & f1.name & " " & vbCrLf
               fso.DeleteFile(f1)
     End If
Next
' === Comment out the below IF statement if you need to run this script in the background
If strComments = "" Then
     WScript.echo " - Files Exist - " & vbCrLf & "But none are old enough for me to delete. Later..."
Else
     WScript.echo strComments
End If
WScript.Quit

No comments:

Post a Comment