Skip to content

Instantly share code, notes, and snippets.

@adamnoffie
Created November 23, 2015 13:45
Show Gist options
  • Save adamnoffie/a50d87a86bf5c61bcdef to your computer and use it in GitHub Desktop.
Save adamnoffie/a50d87a86bf5c61bcdef to your computer and use it in GitHub Desktop.
Recursively Clean up Files/Folders in a directory by the Modified Date (Age) of File
# Function that deletes any files, recursively, from a directory that are older than X days for modified day.
# this is mostly stolen from http://stackoverflow.com/a/19326146/18524
function Cleanup-Dir
{
param([string]$path, [int]$limit)
$minDay = (Get-Date).AddDays(-1 * $limit)
# delete files older than $limit
Get-ChildItem -Path $path -Recurse -Force `
| Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $minDay } `
| Remove-Item -Force -ErrorAction SilentlyContinue
# delete any empty directories left behind after deleting 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 -ErrorAction SilentlyContinue
}
#now, run this cleanup function on ...
Cleanup-Dir "C:\temp" 30
Cleanup-Dir "C:\Users\*\Backup" 14 # powershell can do fancy stuff with regex and wildcards
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment