Tuesday, April 15, 2014

Delete all folders under a sub folder older then X days

Below is a simple PowerShell script which deletes all folders under D:\test older then 2 days.  Have fun!

$Now = Get-Date
$Days = "2"
$TargetFolder = "D:\test"
$LastWrite = $Now.AddDays(-$Days)
d:
cd "D:\test"
$Folders = get-childitem -path $TargetFolder | Where {$_.psIsContainer -eq $true} | Where {$_.LastWriteTime -le "$LastWrite"}

   
foreach ($Folder in $Folders)
   
{
   
write-host "Deleting $Folder" -foregroundcolor "Red"
   
Remove-Item $Folder -recurse -Confirm:$false
   
}
   

1 comment: