管理我的 PowerShell 备份文件
上个月我启动了一个项目来开始备份关键文件夹。这个备份过程只不过是我需要时的另一个恢复选项。尽管如此,它已经运行了一个多月了,我现在有一些完整的备份文件。我不需要保留所有这些。如果我保留 4 个最近的完整备份,那就足够了。以下是我如何使用 PowerShell 管理此过程。
当我创建完整备份文件时,它会被复制到我的 Synology NAS 设备上的共享位置。这就是我现在所拥有的。
如果您还记得的话,每个文件名本质上都包含一组描述;例如脚本和 Dropbox。按上次写入时间对文件进行排序然后相应地删除是很容易的。我有 5 套,可以运行这个:
Get-childitem -Path "\\ds416\backup\20*-full.rar" |
Sort-Object -Property LastWriteTime -Descending |
Select-Object -Skip 20
我这些应该是我可以删除的最旧的文件。不过,我不想做任何假设。如果完整备份一周没有完成或者我手动运行了额外的完整备份怎么办?我需要一种更复杂的方法。我们重来。
首先,获取所有备份文件。
$files = Get-ChildItem -Path "\\ds416\backup\20*-full.rar" -file
接下来,使用正则表达式模式提取备份集名称,对文件进行分组。
$grouped = $files | Group-Object -property { ([regex]"(?<=_)\w+(?=-)").match($_.BaseName).value }
正则表达式正在查找前面有 _ 后面有 - 的文本。这些是lookbehinds 和lookaheads。
现在我可以处理每个组,对文件进行排序并删除最旧的文件。
foreach ($item in $grouped) {
$item.group | Sort-Object -property LastWriteTime -descending | Select-Object -skip 4 | Remove-Item -WhatIf
}
这是我完整的备份修剪 PowerShell 脚本。
#MyBackupTrim.ps1
#trim full backups to the last X number of files
[cmdletbinding(SupportsShouldProcess)]
Param(
[Parameter(Position = 0, HelpMessage = "Specify the backup folder location")]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path $_ })]
[string]$Path = "\\ds416\backup",
[Parameter(HelpMessage = "Specify a file pattern")]
[ValidateNotNullOrEmpty()]
[string]$Pattern = "*-FULL.rar",
[Parameter(HelpMessage = "Specify the number of the most recent files to keep")]
[Validatescript({ $_ -ge 1 })]
[int]$Count = 4
)
$find = Join-Path -Path $path -ChildPath $pattern
Write-Verbose "Finding backup files from $Find"
Try {
$files = Get-ChildItem -Path $find -file -ErrorAction Stop
}
Catch {
Throw $_
}
if ($files.count -gt 0) {
Write-Verbose "Found $($files.count) backup files"
# group the files based on the naming convention
# like 20191108_documents-FULL.rar and 20191108_Scripts-FULL.rar
# but make sure there are at least $Count number of files
$grouped = $files | Group-Object -property { ([regex]"(?<=_)\w+(?=-)").match($_.BaseName).value } | Where-Object { $_.count -gt $count}
if ($grouped) {
foreach ($item in $grouped) {
Write-Verbose "Trimming $($item.name)"
$item.group | Sort-Object -property LastWriteTime -descending | Select-Object -skip $count | Remove-Item
}
}
else {
Write-Host "Not enough files to justify cleanup." -ForegroundColor magenta
}
}
#End of script
我可以将此脚本添加到每周备份脚本的末尾并删除旧文件。我可以定期手动检查我的备份文件夹,以验证我只保留我真正需要的内容。否则我可以放松一下,让 PowerShell 为我完成工作。