' 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 fso.DeleteFile(file.Path), True End If Next End If ' 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 End If Next ' if the folder is empty - delete it If folder.Files.Count = 0 And _ folder.SubFolders.Count = 0 Then 'folder.delete 'to test script, comment out the line above ^, and 'uncomment the line below v WScript.Echo "Delete folder <" & folderName & ">" End If End Function
From novice to tech pro — start learning today.