Delete files within subfolders older than a certain period using PowerShell

In keeping true to the concept of this blog, “Follow the life of an ERP developer, one post at a time,” this post allows you to “follow” something that I needed to crush – deleting files older than a specific number of days or hours including subfolders.

Many moons ago, I created an application that created log files capturing event details. The log files’ sole Delete Key In Bluepurpose was to review events and troubleshoot issues when processing these events. The files are saved in a folder structure divided and grouped by Year, Month, and Event Type. The grouping is helpful for troubleshooting and finding specific transactions, but with several types of events and, at times, a decent volume, there can be a decent amount of disk space wasted; realistically, there isn’t a need to keep diagnostic logs forever. The data does become stale after a certain period.
I created this PowerShell script to delete files from a folder and subfolders older than a certain number of hours from the time of script execution:

$sourcepath = 'D:\Archive\'
$CurrDate = Get-Date
$MaxHours = -1200

Foreach($folder in (Get-ChildItem $sourcepath -Recurse  | where {  $_.PSIsContainer }))
    #"Folder: $folder"
    Foreach($file in (Get-ChildItem $folder.FullName | where { ! $_.PSIsContainer }))
	#"File: $file"
        if($file.LastWriteTime -lt ($CurrDate).AddHours($MaxHours))
	        #"Filter File: $file"
            Write-Host -ForegroundColor Yellow ($file.FullName) 
            Remove-Item $file.FullName

If you want to specify the number of days, replace:

if($file.LastWriteTime -lt ($CurrDate).AddHours($MaxHours))


if($file.LastWriteTime -lt ($CurrDate).AddDays($MaxDays))

Remember to replace the $MaxHours variable with $MaxDays.

Leave a Reply

Your email address will not be published.