Computers & ProgrammingComputers & NetworkingWindows

How to Delete Files Older than “x” Days Old

This VBScript can be used to delete files in a folder that are older than a certain number of days compared to the file’s Last Modified Date. This example collects input from the user regarding the source folder, log file name, and the number of days to compare the file’s last modified timestamp.

Please note that this script will DELETE files.  Be careful as there is not much code listed below to validate what you are entering. If you provide the program with incorrect inputs, you can delete files that were not intended to be targeted.

'vbscript to delete files older than a given number of days.
'WARNING: Deleted files will not be stored in the recycle bin
'
'Declare variables
Dim LogFile
'
'----- Start Main Sub -----
Main
Sub Main()
SourceFolderNamePath=inputbox("Enter the Source Path, ex. C:\Test\")
LogFileNamePath=inputbox("Enter the LogFile Name Path, ex. C:\Logs\Deleted.TXT")
DeleteDaysOld=CInt(inputbox("Enter the number of days in which a file should be deleted if older, ex. 30"))
Call DeleteOldFiles(SourceFolderNamePath,LogFileNamePath,DeleteDaysOld)
End Sub
'
Sub DeleteOldFiles(SourceFolder, logfile, days)
Dim fso,f,f1,s,fi, cnt, tot
'
LogOpen(logfile)
LogWrite "------------------------------------------------------"
LogWrite " Program Started...Searching for Files to Remove "
LogWrite "------------------------------------------------------"
cnt = 0
tot = 0
'
Const ReadOnly = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(SourceFolder)
Set fc = f.Files
For Each f1 in fc
If DateDiff ("d",f1.DateLastModified, Now ) > days Then
LogWrite f1.name & " DateLastModified:" & f1.DateLastModified & " DaysOld:" & DateDiff ("d",f1.DateLastModified, Now )
If f1.Attributes And ReadOnly Then
f1.Attributes = f1.Attributes Xor ReadOnly
End If 

fso.DeleteFile (SourceFolder & f1.name)
cnt = cnt + 1End If
tot = tot + 1
Next
LogWrite "--------------------------------------------------------------"
LogWrite " Processed " & tot & " file(s). Deleted " & cnt & " file(s). "
LogWrite "--------------------------------------------------------------"
LogClose
MsgBox("Delete process completed successfully." + vbCRLF + "Please review the log file at " + logfile)
'
End Sub
'
'
Sub LogOpen (LogPath)
Dim fso, f1
Const ForAppend = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set LogFile = fso.OpenTextFile(LogPath, ForAppend, True)
Set fso = nothing
End Sub
'
Sub LogWrite (Text)
LogFile.WriteLine "[" & Now & "] " & Text
End Sub
'
'
Sub LogClose ()
LogFile.Close
Set Logfile=nothing
End Sub

Leave a Comment

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

Scroll to Top