Delete files & Directories older then n days

To delete files and directories older then a specified days, use the following vbs script:

'
'delete folders specified in a number of days, also specified in the script.
'
On error resume next

Dim Directory
Dim Noofdays
Dim FSO
Dim FSO2
Dim LogFile
Dim Folderlist
Dim folders

Directory ="D:\Logs\directory"
Noofdays=cint(31)
LogFile="D:\logs\result.txt"

Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO2 = CreateObject("Scripting.FileSystemObject")
Set oFSO = CreateObject("Scripting.FilesyStemObject")
'
If oFSO.FileExists(Logfile) Then
Const ForAppending = 8
Set ofile = oFSO.OpenTextFile(LogFile, ForAppending, True)
Else
Set oFile = oFSO.CreateTextFile(logfile, true)
End If
ofile.writeline "Delete Folders older than 31 days Started   --> " & now()

Set Folderlist = FSO.GetFolder(Directory)

Set folders = Folderlist.SubFolders
For Each d In Folders
'          msgbox d.name
'          msgbox d.size
'          msgbox d.dateCreated
'          msgbox d.dateLastModified
'          msgbox d.dateLastAccessed
tempdirectory = Directory & d.name

If  datediff("d",d.dateCreated,now()) > Noofdays Then
FSO2.DeleteFolder(tempdirectory )
ofile.writeline "Deleting Folder...." & tempdirectory

if err.number <>0 then
ofile.writeline cstr(now()) & "    " & Err.description
err.clear
end if
End If
Next
ofile.writeline "Delete Folders older than 31 days Completed --> " &now()
ofile.writeline "--------------------------------------------"
ofile.close

Leave a Reply

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