Script: Delete files older then x days.
The other day I got a question if they could delete files in a folder older then 7 days automaticlly. I solved the question with a script and a scheduled task. And I thought id share the script with you. I would like to thank Fredrik Wall for script review.
‘This is a script to delete files older then specified days
Option Explicit
Dim oFSO
Dim sDirectoryPath
Dim oFolder
Dim oFileCollection
Dim oFile
Dim iDaysOld‘iDaysold = NumberofDays
iDaysOld = 7‘sDirectoryPath = “Folder to deleteFiles in”
sDirectoryPath = “C:Tempforanexample”On Error Resume Next
Set oFSO = CreateObject(“Scripting.FileSystemObject”)
If objFSO.FolderExists(sDirectoryPath) Then
Set oFolder = oFSO.GetFolder(sDirectoryPath)
Set oFileCollection = oFolder.FilesFor each oFile in oFileCollection
If oFile.DateLastModified < (Date() – iDaysOld) Then
oFile.Delete(True)
End If
Next
else
WScript.Echo “No Folder”
End IfSet oFSO = Nothing
Set oFolder = Nothing
Set oFileCollection = Nothing
Set oFile = Nothing