VBScript to remove files based on age

Sometimes it's necessary to delete files based on age, and we can use a VB Script to do that:

'On Error Resume Next ' < -- Comment out for troubleshooting.

Const strPath = "C:\SQL_Backups\SOG-NADC-SP-DB1" ' Update this parent folder.
Const iDaysOld = 2   

' PURPOSE:	This script will delete all files recursively starting from
'			strPath older than 2 days and empty subfolders.
'			Very convenient for cleaning temp and log files.
' WARNING:	Please understand the risks of using this script.
' WARNING:	DO NOT MODIFY BELOW UNLESS YOU KNOW WHAT YOU ARE DOING.

Dim objFolder, objSubFolder, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.getFolder(strPath)

Call Search(objFolder)

Sub Search(objFolder)
	For Each objFile In objFolder.files
		If dateDiff("d",objFile.dateLastModified,Now) > iDaysOld Then objFile.Delete
	Next
	For Each objSubFolder In objFolder.SubFolders
		Search(objSubFolder)
	Next

End Sub

'  end of file

Leave a Reply

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