#----- define parameters -----#
#----- get current date ----#
$Now = Get-Date
#----- define amount of days ----#
$Days = "3"
#----- define folder where files are located ----#
$TargetFolder = "C:\test2"
#----- define extension ----#
$Extension = "*.*"
#----- define LastWriteTime parameter based on $Days ---#
$LastWrite = $Now.AddDays(-$Days)
#----- get files based on lastwrite filter and specified folder ---#
$Files = Get-ChildItem $TargetFolder -Include $Extension -Recurse |
Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($File in $Files) {
if ($File -ne $NULL) {
Write-Host "Deleting File $File" -ForegroundColor "Red"
Remove-Item $File.FullName | Out-Null
} else {
Write-Host "No more files to delete!" -foregroundcolor "Green"
}
}
This is a good PowerShell script to delete files older than X number of days, but we would like to delete multiple files saved at different locations with different number of days for each path.
For example, if we have to delete files older than 3 days then we can just add another location like this example:
$TargetFolder = "C:\test","C:\test2"
and it will take care of both the folders, but we would like to know if there's a way we can have to keep different number of days set for different folders.
In ksh
we used to do it this way in config file:
Location 1;//Server1/c$/processed;14 Location 2;//Server2/backup/;3