备份文件删除程序



我有一个满是备份文件的目录,但由于空间不足,需要自动清理该目录。最简单的方法是使用powershell脚本。

备份每天创建2个备份。我想在7天内每天保留2个备份,超过7天但不超过3个月的备份我想每天保留1个,超过3个月中的所有备份我想每周保留1个。超过2岁的孩子都会被删除。

我写的第一个函数删除了2年以上的所有内容:

$checkPath = "C:demo"
$list = (Get-ChildItem -Path $checkPath | Where-Object {$_.LastWriteTime -lt (Get-Date).AddYears(-2)}).FullName
$count = $list.Length
for ($i = 0; $i -lt $count; $i += 1)
{
Write-Verbose "[$i] $($list[$i])"
Remove-Item -Path $list[$i] 
}

在那之后,我创建了一个函数来删除每2个备份:

$checkPath = "C:demo"
$list = (Get-ChildItem -Path $checkPath | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-7)} | Where-Object {$_.LastWriteTime -lt (Get-Date).AddMonths(-3)}).FullName
$count = $list.Length
for ($i = 0; $i -lt $count; $i += 2)
{
Write-Verbose "[$i] $($list[$i])"
Remove-Item -Path $list[$i] 
}

我觉得有点迷失了方向,我走对了吗?有人可能有这样做的建议吗;更好";?

同样,除了代码中的内容外,不会做太多细节。希望这些评论足够响亮

$checkPath = 'C:temp'
$classified = switch ((Get-ChildItem -Path $checkPath -File | Group-Object { $_.LastWriteTime.Date }) ) {
# Last 7 days
{ [datetime]::Parse(($_.Name)) -ge [datetime]::Today.AddDays(-7) } {
$keep = $_.group | Sort-Object LastWriteTime | Select-Object -Last 2
$keep | ForEach-Object {
[pscustomobject]@{Path = $_.fullname; LastWriteTime = $_.LastWriteTime; Action = 'Keep'; Interval = '<= 7 days' }
}
$remove = $_.group | Where-Object { $_ -notin $keep }
$remove | ForEach-Object {
[pscustomobject]@{Path = $_.fullname; LastWriteTime = $_.LastWriteTime; Action = 'Remove'; Interval = '<= 7 days' }
}
}
{ [datetime]::Parse(($_.Name)) -lt [datetime]::Today.AddDays(-7) -and
[datetime]::Parse(($_.Name)) -ge [datetime]::Today.AddMonths(-3) } {
# Between 7 days and 3 months $_.Name -ForegroundColor Green
$keep = $_.group | Sort-Object LastWriteTime | Select-Object -Last 1
$keep | ForEach-Object {
[pscustomobject]@{Path = $_.fullname; LastWriteTime = $_.LastWriteTime; Action = 'Keep'; Interval = 'Between 7 days and 3 months' }
}
$remove = $_.group | Where-Object { $_ -notin $keep }
$remove | ForEach-Object {
[pscustomobject]@{Path = $_.fullname; LastWriteTime = $_.LastWriteTime; Action = 'Remove'; Interval = 'Between 7 days and 3 months' }
}
}
{ [datetime]::Parse(($_.Name)) -lt [datetime]::Today.AddMonths(-3) -and
[datetime]::Parse(($_.Name)) -ge [datetime]::Today.AddYears(-2) } {
# Between 3 months and 2 years $_.Name -ForegroundColor Green
# Set to unknown for now.  Group by weekOfYear later to make determination
$_.group | ForEach-Object {
[pscustomobject]@{Path = $_.Fullname; LastWriteTime = $_.LastWriteTime; Action = 'Unknown'; Interval = 'Between 3 months and 2 years' }
}
}
Default {
$_.group | ForEach-Object {
# Everything after 2 years $_.Name -ForegroundColor Green
[pscustomobject]@{Path = $_.fullname; LastWriteTime = $_.LastWriteTime; Action = 'Remove'; Interval = '> 2 years' }
}
}
}
# Needed to determine and group by week of year
$cultureInfo = [cultureinfo]::new('en-US')
$calendar = $cultureInfo.Calendar;
$calendarRule = $cultureInfo.DateTimeFormat.CalendarWeekRule
$firstDayOfWeek = $cultureInfo.DateTimeFormat.FirstDayOfWeek

$classified | Where-Object Interval -EQ 'Between 3 months and 2 years' |
# Group all files between 3 months and 2 years by weekOfYear and Year and set latest one to keep, others to remove
Group-Object { $calendar.GetWeekOfYear($_.LastWriteTime, $calendarRule, $firstDayOfWeek) }, { $_.LastWriteTime.Year } |
ForEach-Object {
$keep = $_.group | Sort-Object LastWriteTime | Select-Object -Last 1
$keep | ForEach-Object { $_.Action = 'Keep' }
$remove = $_.group | Where-Object { $_ -notin $keep }
$remove | ForEach-Object { $_.Action = 'Remove' }
}
$classified | Sort-Object LastWriteTime | Out-Host
$classified | Where-Object Action -EQ 'Remove' | Remove-Item -WhatIf

输出

Path                                                      LastWriteTime       Action Interval
----                                                      -------------       ------ --------
C:temp20210101 - 20210108.pdf                           13.01.2021 09:15:22 Keep   Between 3 months and 2 years
C:temp20210115 - 20210122.pdf                           26.01.2021 15:57:47 Keep   Between 3 months and 2 years
C:temprm_50117.pbl                                      14.05.2021 15:26:41 Keep   Between 7 days and 3 months
C:tempzipped.zip                                        19.05.2021 18:35:12 Remove Between 7 days and 3 months
C:tempzipped2.zip                                       19.05.2021 18:40:54 Remove Between 7 days and 3 months
C:tempzipped3.zip                                       19.05.2021 18:46:05 Keep   Between 7 days and 3 months
C:tempxxx_Some Doc ID 2333 _other stuff_more stuff.junk 20.05.2021 23:32:43 Keep   Between 7 days and 3 months
C:temptestlksj.ps1                                      21.05.2021 22:28:03 Keep   Between 7 days and 3 months
C:tempskdljfsdkf.ps1                                    22.05.2021 09:04:29 Remove Between 7 days and 3 months
C:temptestparam.ps1                                     22.05.2021 17:08:33 Remove Between 7 days and 3 months
C:tempgitignorepath.txt                                 22.05.2021 21:03:06 Keep   Between 7 days and 3 months
C:templslkdfjl.ps1                                      23.05.2021 00:56:13 Remove Between 7 days and 3 months
C:temptest2.txt                                         23.05.2021 10:17:24 Remove Between 7 days and 3 months
C:temptest3.txt                                         23.05.2021 10:17:38 Remove Between 7 days and 3 months
C:temptest4.txt                                         23.05.2021 10:17:50 Keep   Between 7 days and 3 months
C:tempfromVS.txt                                        24.05.2021 22:57:44 Keep   <= 7 days
C:temptestlksfsdfsdj.ps1                                25.05.2021 16:55:45 Keep   <= 7 days
C:tempdslkfjlds.ps1                                     26.05.2021 23:35:23 Keep   <= 7 days
C:tempslkfjdslfj.ps1                                    27.05.2021 00:35:09 Keep   <= 7 days
C:temptestgit.log                                       31.05.2021 13:28:19 Keep   <= 7 days
C:tempout.log                                           31.05.2021 13:51:37 Keep   <= 7 days
What if: Performing the operation "Remove File" on target "C:tempzipped.zip".
What if: Performing the operation "Remove File" on target "C:tempzipped2.zip".
What if: Performing the operation "Remove File" on target "C:tempskdljfsdkf.ps1".
What if: Performing the operation "Remove File" on target "C:temptestparam.ps1".
What if: Performing the operation "Remove File" on target "C:templslkdfjl.ps1".
What if: Performing the operation "Remove File" on target "C:temptest2.txt".
What if: Performing the operation "Remove File" on target "C:temptest3.txt".

我不想在这里详细介绍,只需查看代码并阅读注释即可。

需要考虑的一件事是,在Get-ChildItem "C:demo" -File上,您可能需要考虑使用-Filter仅筛选具有备份扩展名的文件。

请注意,我在Remove-Item上使用-WhatIf标志,请查看脚本,如果您认为它正在执行您想要的操作,请删除此标志。

# Group all backups per day
# DateTime Format MM/dd/yyyy 12:00:00 AM
$backups = Get-ChildItem 'C:demo' -File |
Group-Object {$_.CreationTime.Date} |
Sort-Object -Descending {$_.Name -as [datetime]}

$date = [datetime]::Now

$onePerWeekGroups = foreach($group in $backups)
{
switch($group)
{
{[datetime]$_.Name -ge $date.AddDays(-7)}
{
# Groups which Date is greater than or equal to
# Date 7 Days ago

# For this group (day), skip the first 2 backups and
# remove the rest
$_.Group | Select-Object -Skip 2 | Remove-Item -WhatIf

break
}

{[datetime]$_.Name -lt $date.AddDays(-7) -and [datetime]$_.Name -ge $date.AddMonths(-3)}
{
# Groups which Date is lower than Date 7 Days ago and
# greater than or equal to Date 3 Months ago

# For this group (day), skip the first backup and
# remove the rest
$_.Group | Select-Object -Skip 1 | Remove-Item -WhatIf

break
}
{[datetime]$_.Name -lt $date.AddMonths(-3) -and [datetime]$_.Name -ge $date.AddYears(-2)}
{
# Groups which Date is lower than Date 3 Months ago and
# greater than or equal to Date 2 Years ago

# Since this Group has more complexity than the others, 
# will return this groups and store them in $onePerWeekGroups for later 
return $_
}
Default
{
# Groups which Date is higher than 2 Years

# For this group, remove everything
Remove-Item -Path $_.Group.FullName -WhatIf
}
}
}

$calendar = (Get-Culture).Calendar

# Group all files by Year (Thanks Daniel for pointing this out)
# and by Week
$groupsPerWeek = $onePerWeekGroups.Group | Group-Object {
$calendar.GetWeekOfYear(
$_.CreationTime,
[System.Globalization.CalendarWeekRule]::FirstFourDayWeek,
[DayOfWeek]::Monday
)}, {$_.CreationTime.Year}

foreach($group in $groupsPerWeek)
{
# Skip the first file of this Week and Remove the rest
$group.Group | Select-Object -Skip 1 | Remove-Item -WhatIf
}

最新更新