如果最新的文件大小不小,请删除旧的备份文件

Delete old backup files if the newest file size isn't to small

我正在尝试创建一个 powershellscript 来安排备份删除,这样 HDD 就不会变满。

我希望你们帮我想想我应该如何制定代码才能使它起作用。

我从下面开始,它删除了超过 2 天的所有文件,但我不太确定如何更改它以保留最新文件而不取决于天数。

$Path = "C:\Temp\Backup\Folder1\"
$Days = 2
$Date = Get-Date
$Include = "*.gpg"
$Exclude = "*.txt"

Get-ChildItem $Path -Recurse |
Where-Object {-not $_.PSIsContainer -and $Date.Subtract($_.CreationTime).Days -gt $Days } |
Remove-Item -WhatIf

你可以这样做:

$BackupFiles = Get-ChildItem -File | Sort-Object LastWriteTime -Descending

$LatestBackup = $BackupFiles | Select -First 1
$PrevBackup = $BackupFiles | Select -Skip 1 -First 1

$BackupSizeThreshold = $PrevBackup.Length * 0.1


$FilesToRemove = If ($LatestBackup.Length -le ($PrevBackup.Length + $BackupSizeThreshold) -and $LatestBackup.Length -ge ($PrevBackup.Length - $BackupSizeThreshold)) {
    $BackupFiles | Select -Skip 1
}
Else {
    $BackupFiles | Select -Skip 2
}

$FilesToRemove | Remove-Item -WhatIf

如果您看到了预期的结果,请删除 -WhatIf