Menu

VBscript delete files and folders older than X days

Updated: November 1, 2013

Ali Taheri

Here's how you can quickly delete files and folders older than however many days you choose. This is based on the date the file was created. In the example below, data more than 50 days old is deleted. At the same time, so are empty folders and files in nested folders.

 

Const strPath = "D:\My Backups"
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")

Call Search (strPath)

' Comment out below line if you'd like to use this script in windows schedule task
WScript.Echo"Done."

Sub Search(str)
	Dim objFolder, objSubFolder, objFile
	Set objFolder = objFSO.GetFolder(str)
	For Each objFile In objFolder.Files

		' Use DateLastModified for modified date of a file
		If objFile.DateCreated < (Now() - 50) Then
			objFile.Delete(True)
		End If

	Next
	For Each objSubFolder In objFolder.SubFolders
		Search(objSubFolder.Path)

		' Files have been deleted, now see if the folder is empty.
		If (objSubFolder.Files.Count = 0) Then
			objSubFolder.Delete True
		End If

	Next
End Sub

Tags

VBscript
comments powered by Disqus

© 2017 - Ali Sheikh Taheri