Recursively delete outdated files with VBScript

Recently, I came across the situation, where I had to delete outdated SQL backup files from our MS SQL servers Backup directory. To tidy up the backup folder, I wrote a small VB script which handles this for me:


' DeleteOutdated
'
' Parameters
' MaxFileAge: Maximum file age in days (modification date)
' Path: Folder which contains the files
'
' VBScript ref. http://msdn.microsoft.com/en-us/library/t0aew7h6(VS.85).aspx
' FSO ref. http://msdn.microsoft.com/en-us/library/z9ty6h50(VS.85).aspx

Dim objFso
Set objFso = CreateObject("Scripting.FileSystemObject")

Sub DeleteOutdated(Path, MaxFileAge)
	Set objDir = objFso.GetFolder(Path)
	For Each objFile in objDir.Files
		If objFile.DateLastModified < (Date() - MaxFileAge) Then
			AskDelete = MsgBox("Delete "&objFile.Path&"?",3,"Delete file")
			If AskDelete = 6 Then
				objFile.Delete
			End If
			If AskDelete = 2 Then
				WScript.Quit
			End If
		End If
	Next

	For Each objSubfolder in objDir.Subfolders
		Call DeleteOutdated(objSubfolder, MaxFileAge)
	Next
End Sub

Call DeleteOutdated("c:\outdatedstuff", 1)

Hint
In this state, the script asks to delete everytime, if it finds a file wich is older than specified. Of course, you might want to remove that in productive usage, when script execution is scheduled.

Extended
Here I attached a version, which writes a logfile and processes empty subfolders (updated on 26.08.2009):
deleteoutdated-wlog

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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