Script to delete all files over a specified age in a folder and its sub folders

The below script will delete all file in a folder over a certain ago and repeat the task for the folders sub folders

Change the variables startFolder and OlderThanDate as needed.

PowerShell Method

If you only want to evaluate what would happen if the script ran, add the parameter -WhatIf before the end brace.

$startFolder = "C:\Source_Folder"
$olderThanDate = 7

get-childitem $startFolder -recurse | where {$_.lastwritetime -lt (get-date).adddays(-$olderThanDate) -and -not $_.psiscontainer} |% {remove-item $_.fullname -force -verbose}

VBS Method

Dim fso, startFolder, OlderThanDate
Set fso = CreateObject("Scripting.FileSystemObject")
startFolder = "c:\Source_Folder\" ' folder to start deleting (subfolders will also be cleaned)
OlderThanDate = DateAdd("d", -7, Date)  ' 7 days (adjust as necessary)
DeleteOldFiles startFolder, OlderThanDate
Function DeleteOldFiles(folderName, BeforeDate)
   Dim folder, file, fileCollection, folderCollection, subFolder
   Set folder = fso.GetFolder(folderName)
   Set fileCollection = folder.Files
   For Each file In fileCollection
      If file.DateLastAccessed < BeforeDate Then
      End If
    Set folderCollection = folder.SubFolders
    For Each subFolder In folderCollection
       DeleteOldFiles subFolder.Path, BeforeDate
End Function

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.