Hi, I have a batch file that works great for deleting old files in folders then deleting the empty folder. However, I need to modify it so that it only deletes the folder if it's older than a certain date, regardless of how old the files inside the folder are.
Also, to accomplish a separate task, how could this be modified to delete everything inside a folder except .zip files?
' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Enter your folder to start deleting files from
startFolder = "R:\WEB BACKUPS\"
' Enter the names of folders to exclude from checking:
arrFoldersToExclude = Array("Sync")
strFoldersToExclude = ";" & Join(arrFoldersToExclude, ";") & ";"
' This sets the amount of days old for files to be, before
' they are deleted. The number must be negative.
OlderThanDate = DateAdd("d", -45, Date) ' 90 days (adjust as necessary)
' This calls the function that actually deletes the files.
DeleteOldFiles startFolder, OlderThanDate
Function DeleteOldFiles(folderName, BeforeDate)
Dim folder, file, fileCollection, folderCollection, subFolder
' Get the folder to delete files from
Set folder = fso.GetFolder(folderName)
If InStr(LCase(strFoldersToExclude), ";" & LCase(folder.Name) & ";") = 0 Then
' Return a collection of all of the files in that folder
Set fileCollection = folder.Files
' Go through each file....
For Each file In fileCollection
' ... to check if the DateLastModified value is before
' the minimum age of files to delete.
If file.DateLastModified < BeforeDate Then
' Get the next collection of SubFolders to go through
Set folderCollection = folder.SubFolders
' Go through each SubFolder
For Each subFolder In folderCollection
' Check if the current folder name is in the strFoldersToExclude string
If InStr(LCase(strFoldersToExclude), ";" & LCase(fso.GetFolder(foldername).Name) & ";") = 0 Then
' If it's not, delete the files from that folder
DeleteOldFiles subFolder.Path, BeforeDate
' if the folder is empty - delete it
If folder.Files.Count = 0 And _
folder.SubFolders.Count = 0 Then
'to test script, comment out the line above ^, and
'uncomment the line below v
WScript.Echo "Delete folder <" & folderName & ">"