PowerShell Delete files older than x amount of days from Downloads

  • Welcome to ITBible, we're your #1 resource for enterprise or homelab IT problems (or just a place to show off your stuff).
Pretty simple script, this just remove files from your downloads folder that are older than x amount of days (by default its set to 60).

PowerShell:
$Paths = @(
    "%userprofile%\Downloads\"
)
$Days = 60

$limit = (Get-Date).AddDays(-$Days)
foreach ($Path in $Paths)
{
    # Delete files older than the $limit.
    Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
    
    # Delete any empty directories left behind after deleting the old files.
    Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
}
 
  • Like
Reactions: Andy