问题
I'm using this powershell command to keep only backup files that are 31 days old.
Get-ChildItem –Path “d:\Backup\hl” –Recurse | Where-Object{$_.LastWriteTime –lt (Get-Date).AddDays(-31)} | Remove-Item -Force -Recurse
My question is if the daily backup was to fail and I checked the backup folder e.g after a month, the powershell script would delete all or most of the backups because they are older then 31 days.
Is it possible to change the powershell command to keep the last 31 files depending on lastwritetime , but not because they are within 31 days old?
Thanks
回答1:
You can do the following, I'm not sure how this will behave with your recurse parameter but assume it is working correctly so I have left it in the example:
Get-ChildItem –Path “d:\Backup\hl” –Recurse | Sort-Object LastWriteTime –Descending | Select-Object -Skip 31 | Remove-Item -Force -Recurse
回答2:
Sort by LastWriteTime
and skip the first 31 files. When using -Recurse
, foldernames would also appear in the result. So to keep the last 31 FILES, you need to exclude the folder-items using Where-Object
, like:
Get-ChildItem –Path “d:\Backup\hl” –Recurse |
Where-Object { !$_.PSIsContainer } |
Sort-Object LastWriteTime -Descending |
Select-Object -Skip 31 |
Remove-Item -Force -Recurse
来源:https://stackoverflow.com/questions/23735890/powershell-keep-last-31-files