Noffie

Cleanup Directory for files older than X days

Nov 20th, 2015
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # this is mostly stolen from http://stackoverflow.com/a/19326146/18524
  2. function Cleanup-Dir
  3. {
  4.     param([string]$path, [int]$limit)
  5.  
  6.     $minDay = (Get-Date).AddDays(-1 * $limit)
  7.  
  8.     # delete files older than $limit
  9.     Get-ChildItem -Path $path -Recurse -Force `
  10.         | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $minDay } `
  11.         | Remove-Item -Force -ErrorAction SilentlyContinue
  12.  
  13.     # delete any empty directories left behind after deleting old files
  14.     Get-ChildItem -Path $path -Recurse -Force `
  15.         | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } `
  16.         | Remove-Item -Force -ErrorAction SilentlyContinue
  17. }
  18.  
  19. Cleanup-Dir "C:\temp" 10
  20. Cleanup-Dir "C:\IntactStorage\Collectors\*\Backup" 14
  21. #Cleanup-Dir "C:\IntactStorage\Storage\Temp" 3
  22. #Cleanup-Dir "C:\IntactStorage\Temp" 1
Advertisement
Add Comment
Please, Sign In to add comment