我有一个存放文件夹和文件的位置。我需要使这个脚本工作,以便它删除该路径内所有超过 X 天的内容,但始终保留 Y 数量的文件夹,以免删除所有内容,即使文件夹超过 X 天,也应该始终存在他们中的一些人离开了。这是我到目前为止。该脚本有效,但我不断收到红色错误,因为文件已被删除,因此 remove-item 无法找到该文件,我不知道如何删除它们
$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
}
}
答案 0 :(得分:0)
$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