Powershell保留最后31个文件 [英] powershell keep last 31 files
问题描述
我正在使用此powershell命令仅保留31天的备份文件.
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
我的问题是,如果每日备份是否失败,并且例如在一个月后检查了备份文件夹,则Powershell脚本将删除全部或大部分备份,因为它们的日期早于31天.
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.
是否可以根据lastwritetime更改powershell命令以保留最后31个文件,但不是因为它们存在31天之内?
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?
谢谢
推荐答案
按LastWriteTime
排序,然后跳过前31个文件.使用-Recurse
时,文件夹名称也将出现在结果中.因此,要保留最后31个文件,您需要使用Where-Object
排除文件夹项,例如:
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
这篇关于Powershell保留最后31个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!