Using PowerShell, you can create a scheduled task to automatically delete files older than a few days in a specific folder.
This is useful for scan, logs, or download folders, because these folders can easily store a large amount of files if we don’t remove the files as we no longer require them.
Let's configure a PowerShell script to clean up our Download folder so that files are removed after 15 days.
$targetDirectory = "C:\Users\User\Downloads"
$daysThreshold = 15
$cutoffDate = (Get-Date).AddDays(-$daysThreshold)
if (-Not (Test-Path -Path $targetDirectory)) {
exit 1
}
Get-ChildItem -Path $targetDirectory -File | Where-Object {
$_.CreationTime -lt $cutoffDate -and -not $_.Name.StartsWith("!")
} | Remove-Item -Force
Lines 1 and 2 should be modified to your needs.
With this script, we also skip the files that start with an exclamation mark !. This allows us to create a file like:
! The files will be removed after 15 days.txt
So everyone knows the files in this folder won’t last forever.