I have location that holds folders and files within those folders. I need to make this script work so that it deletes all inside of that path that is older than X amount of days but always leave Y amount of folders as to not delete everything, even if the folders are older than X days there always should be some of them left. This is what i have so far. The script works but I keep getting red errors how remove-item can't find the file since it has been deleted and i do not know how to remove them
$rententionDays = -15
$FoldersToKeep= 5
$Location = "C:\Users\user\Desktop\test"
$FolderList = Get-ChildItem $Location
foreach($folder in $FolderList ){
if($folder.CreationTime -gt $folder.CreationTime.AddSeconds($rententionDays)){
$FolderList | select -Skip $buildsToKeep | Remove-Item
}
}
$DaysToKeep = -15
$FoldersToKeep = 5
$Location = 'C:\Users\user\Desktop\test'
$FolderList = Get-ChildItem -Path $Location -Directory # -Recurse # Probably didn't mean to include subfolders with recurse.
# They will be deleted along with parent folders
$FolderList | Sort-Object CreationTime -Descending |
Select-Object -Skip $FoldersToKeep | # First skip the folders to be kept no matter what
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays($DaysToKeep) } | # Check remaining folder lastwrite and if less than today - 15 days send down pipe
Remove-Item -WhatIf
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.