-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRetentionPolicy.psm1
More file actions
267 lines (233 loc) · 8.77 KB
/
RetentionPolicy.psm1
File metadata and controls
267 lines (233 loc) · 8.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 2.0
class RetentionPolicy {
[Int] $Monthly = 99999
[Int] $Weekly = 45
[Int] $Daily = 21
[Int] $IntraDaily = 3
}
function New-RetentionPolicy {
<#
.SYNOPSIS
Sets up the retention policy used by Start-RetentionPolicyCleanup.
.EXAMPLE
$policy = New-RetentionPolicy
.EXAMPLE
$policy = New-RetentionPolicy -Weekly 45 -Daily 14 -IntraDaily 3
.EXAMPLE
$policy = New-RetentionPolicy -Monthly 24 -Weekly 45 -Daily 14 -IntraDaily 3
#>
[CmdletBinding()]
param (
# Number of days to retain monthly files
[Int]
$Monthly = 99999,
# Number of days to retain weekly files
[Int]
$Weekly = 45,
# Number of days to retain daily files
[Int]
$Daily = 21,
# Number of days to retain intradaily files
[Int]
$IntraDaily = 21
)
process {
return [RetentionPolicy]@{
Monthly = $Monthly
Weekly = $Weekly
Daily = $Daily
IntraDaily = $IntraDaily
}
}
}
function Initialize-RetentionPolicy {
<#
.SYNOPSIS
Checks an input array against a retention policy and adds properties to the output
.EXAMPLE
Initialize-RetentionPolicy
#>
[CmdletBinding()]
param (
# Retention policy to use. Created with New-RetentionPolicy
[Parameter(Mandatory)]
[RetentionPolicy]
$Policy,
# Objects to process from the pipeline
[Parameter(Mandatory, ValueFromPipeline)]
[PSObject[]]
$InputObject,
# Property to use for date matching and sorting.
[Parameter(Mandatory)]
[String]
$DateProperty,
# Use this if you prefer to keep the newest file from each time window.
[Switch]
$PreferNewest
)
begin {
$objects = New-Object System.Collections.Generic.List[PSObject]
}
process {
foreach ($object in $InputObject) {
if ($object.$DateProperty -isnot [DateTime]) {
throw "$DateProperty is not a valid [DateTime] for $object"
}
$objects.Add($object)
}
}
end {
$objects = $objects | Sort-Object $DateProperty -Descending:$PreferNewest
$now = Get-Date
$found = New-Object System.Collections.Generic.List[String]
foreach ($object in $objects) {
$date = $object.$DateProperty
$isoDate = ConvertTo-IsoDate -InputObject $date
$yearMonthDay = $isoDate.IsoDateFormat
$yearMonth = "$( $date.year )-$( $date.month )"
$yearWeek = "$( $isoDate.IsoYear )-$( $isoDate.IsoWeek )"
$retentionReason = @()
if ($date -gt $now.AddDays(-$Policy.Monthly) -and $yearMonth -notin $found) {
$found.Add($yearMonth)
$retentionReason += 'Monthly'
}
if ($date -gt $now.AddDays(-$Policy.Weekly) -and $yearWeek -notin $found) {
$found.Add($yearWeek)
$retentionReason += 'Weekly'
}
if ($date -gt $now.AddDays(-$Policy.Daily) -and $yearMonthDay -notin $found) {
$found.Add($yearMonthDay)
$retentionReason += 'Daily'
}
if ($date -gt $now.AddDays(-$Policy.IntraDaily)) {
$retentionReason += 'IntraDaily'
}
$object | Add-Member -MemberType NoteProperty -Name 'Retain' -Value ($retentionReason.Count -gt 0)
$object | Add-Member -MemberType NoteProperty -Name 'RetentionReason' -Value $retentionReason
$object
}
}
}
function Start-RetentionPolicyCleanup {
<#
.SYNOPSIS
Removes old files from a directory except for those matching a retention policy.
.EXAMPLE
$Params = @{
Policy = New-RetentionPolicy -Weekly 45 -Daily 14 -IntraDaily 3
Source = 'C:\Backups'
FileNamePattern = 'prefix_(\d{4}-\d\d-\d\d)_.*\.tgz'
DateProperty = 'FileNamePattern'
MinimumSize = 3500MB
}
Start-RetentionPolicyCleanup @Params -WhatIf
.EXAMPLE
$policy = New-RetentionPolicy -Weekly 45 -Daily 14 -IntraDaily 3
$src = 'C:\Backups'
Start-RetentionPolicyCleanup -Policy $Policy -Source $src -FileNamePattern 'prefix_.*' -DateProperty LastWriteTime
#>
[CmdletBinding(SupportsShouldProcess)]
param (
# Retention policy to use. Created with New-RetentionPolicy
[Parameter(Mandatory)]
[RetentionPolicy]
$Policy,
# Directory to search for files.
[Parameter(Mandatory)]
[String]
$Source,
# Destination to move found backups. If a relative path is given, it's joined with the $Source param.
[String]
$Destination = 'CleanedFiles',
# Only files matching this regular expression will be included in the job. Please make it very specific.
[Parameter(Mandatory)]
[String]
$FileNamePattern,
# Property to use for date matching and sorting.
# If the FileNamePattern is used, it will use the first capture group from the FileNamePattern paramater.
# TODO: This should have auto-complete suggestions but still allow free text fields.
[Parameter(Mandatory)]
[ValidateSet('FileNamePattern', 'CreationTime', 'LastWriteTime')]
[String]
$DateProperty,
# Only work on files bigger than this. PowerShell allows units to be included, eg. 3500MB
# This is used to prevent 0 length files taking up the place of a legitmate file.
[Int64]
$MinimumSize = 10MB,
# Delete files rather than moving them.
[Switch]
$Delete
)
process {
if (-not [System.IO.Path]::IsPathRooted($Destination)) {
$Destination = Join-Path $Source $Destination
}
$destinationExists = Test-Path -PathType Container -Path $Destination
if ($destinationExists -eq $false -and $PSCmdlet.ShouldProcess($Destination, 'Create Destination')) {
$null = New-Item -Path $Destination -ItemType Directory -Force
}
$allFiles = Get-ChildItem -File $Source
#this was used for debuging
#$allFiles = Import-Clixml oldfilelist.xml
$matchingFiles = $allFiles | Where-Object {
$_.Length -gt $MinimumSize -and $_.Name -match $FileNamePattern
}
if ($DateProperty -eq 'FileNamePattern') {
foreach ($file in $matchingFiles) {
$fileNameDate = $file.Name -replace $FileNamePattern, '$1' | Get-Date
$file | Add-Member -NotePropertyName 'FileNamePattern' -NotePropertyValue $fileNameDate
}
}
$files = $matchingFiles | Initialize-RetentionPolicy -Policy $Policy -DateProperty $DateProperty
$filesToRemove = $files | Where-Object { $_.Retain -eq $false }
if ($VerbosePreference -eq 'Continue') {
$filesToKeep = $files | Where-Object { $_.Retain -eq $true }
Write-Verbose ('Cleaning {0} files and retaining {1}.' -f $filesToRemove.Count, $filesToKeep.Count)
}
foreach ($file in $filesToRemove) {
if ($Delete) {
if ($PSCmdlet.ShouldProcess($File.FullName, 'Delete')) {
Remove-Item -Path $File.FullName
}
} else {
if ($PSCmdlet.ShouldProcess($File.FullName, "Move to $Destination")) {
Move-Item -Path $File.FullName -Destination $Destination
}
}
}
}
}
function ConvertTo-IsoDate {
<#
.SYNOPSIS
Converts a DateTime to an object containing ISO date values.
.DESCRIPTION
Required because PowerShell 5.1 returns false ISO Year and ISO Week values.
.EXAMPLE
$date | ConverTo-IsoDate
.EXAMPLE
ConvertTo-IsoDate $date
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline, Mandatory, Position = 0)]
[DateTime]
$InputObject
)
process {
$DayofWeek = [int]$DateTime.DayOfWeek
if ($DayofWeek -eq 0) {
$DayofWeek = 7
}
$Thursday = $DateTime.AddDays(4 - $DayofWeek)
[PSCustomObject]@{
IsoDateFormat = (Get-Date $DateTime -Format 'yyyy-MM-dd')
IsoYear = $Thursday.Year
IsoWeek = 1 + [Math]::Floor(($Thursday.DayOfYear - 1) / 7)
}
}
}
Export-ModuleMember -Function New-RetentionPolicy
Export-ModuleMember -Function Initialize-RetentionPolicy
Export-ModuleMember -Function Start-RetentionPolicyCleanup