Delete files older than x days

Reading Time: < 1 minute

To delete files from a folder older then 21 days for example, copy the below code into a notepad and save as .vbs. e.g. RemoveOldFiles.vbs

Set the number of days as required, the below script is set to delete files older than 21 days from location c:\test

Script below:

On Error Resume Next

Set fso = CreateObject(“Scripting.FileSystemObject”)      

olddate =  DateAdd(“d”, –21, date)

WScript.StdOut.WriteLine(“Today is ” & Date & vbCrLf)
WScript.StdOut.WriteLine(“Deleting files unaccessed since ” & olddate)
WScript.StdOut.WriteLine(” “)

WScript.stdout.writeline(“Connecting to FileShare “)
Set folder = fso.GetFolder(“c:\test“)    ‘ Get the folder
WScript.StdOut.Writeline(“Getting a List of the Files”)
Set fc = folder.Files

For Each f1 in fc
If f1.DateLastModified < olddate Then
WScript.StdOut.WriteLine(“Removing: ” & f1.DateLastModified & vbtab & f1.name)
fso.deletefile(f1)
End If
Next

You could also try https://cloudbuild.co.uk/?p=351

Please follow and like us: