powershell keep last 31 files

泪湿孤枕 提交于 2019-12-11 23:53:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!