Remove files by extension and date

Here you find a little bit of Powershell code to remove files by extension older then an x amount of days.

Clean, not much about it and very useful!

#----- define parameters -----#
#----- get current date ----#
$Now = Get-Date
#----- define amount of days ----#
$Days = "60"
#----- define folder where files are located ----#
$TargetFolder = "[Path\To\Folder]"
#----- define extension ----#
$Extension = "*.ext"
#----- define LastWriteTime parameter based on $Days ---#
$LastWrite = $Now.AddDays(-$Days)

#----- get files based on lastwrite filter and specified folder ---#
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}

foreach ($File in $Files)
if ($File -ne $NULL)
write-host "Deleting File $File" -ForegroundColor "DarkRed"
Remove-Item $File.FullName | out-null
Write-Host "No more files to delete!" -foregroundcolor "Green"

Save this code as a .ps1 file (or download it here) , use this file within your taskmanager and never look back.

Leave a Reply

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

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