PowerShell script to delete sub folders old than certain days
In my previous Blog, I discussed how to use PowerShell script to delete files old than certain days. At the time I was focused on the files (log files in particular). Recently there is a need to do the similar thing for folders like if you have Backup folder contain sub backup folders created on different date. Here is a modified script to get the job done.
Function RemoveOldFile
{
param ($strComputer = $(Read-Host "Please Enter The Server Name")),
($Dir = $(Read-host "Please Enter The Directory Path"))
($Days = $(Read-Host "How Many Days?"))
$TargetFolder = "\\" + $strComputer + "\" + $Dir
if (Test-Path $TargetFolder)
{
#Warn you the targeted folder, so you can double check
Write-host "The Targeted Folder is:" $TargetFolder -foregroundcolor "Red"
Write-Host `a `a `a `a `a
Write-Host "If This Is Not The Intended Target, Press 'Ctrl + C' To Exit" -foregroundcolor "Yellow"
Start-sleep -s 15
$Now = Get-Date
# Notice the minus sign before $days
$LastWrite = $Now.AddDays(-$days)
Get-ChildItem $Targetfolder |Where {$_.LastWriteTime -le "$LastWrite"}|remove-item -recurse
}
Else
{Write-Host "The Folder $TargetFolder Does Not Exist!"}
}
RemoveOldFile
Enjoy!