-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove-OldFile.ps1
More file actions
485 lines (411 loc) · 16.7 KB
/
Copy pathRemove-OldFile.ps1
File metadata and controls
485 lines (411 loc) · 16.7 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
function Remove-OldFile
{
<#
.SYNOPSIS
Removes files older than a specified time period with optional recursion.
.DESCRIPTION
Searches for files older than a specified age and removes them. Supports optional recursion
into subdirectories, filtering by file patterns, excluding specific files/directories, and
optionally removing empty directories after cleanup.
Cross-platform compatible with PowerShell 5.1+ on Windows, macOS, and Linux.
.PARAMETER Path
The root path to search for old files. Defaults to the current directory.
Supports ~ for home directory expansion and accepts pipeline input.
.PARAMETER OlderThan
The age threshold for files to be removed. Files with LastWriteTime older than this
value will be deleted.
.PARAMETER Unit
The time unit for the OlderThan parameter. Valid values: Days, Hours, Months, Years.
Default is Days.
.PARAMETER Include
File name patterns to include (e.g., '*.log', '*.tmp').
Supports multiple patterns as an array. If not specified, all files are considered.
.PARAMETER Exclude
File name patterns to exclude (e.g., '*.keep', 'important*').
Supports multiple patterns as an array.
.PARAMETER ExcludeDirectory
Directory names to exclude from the search (e.g., '.git', 'node_modules').
These directories and their subdirectories will not be searched.
Supports multiple patterns as an array.
.PARAMETER Recurse
When specified, searches subdirectories recursively. Without this switch, only the
files directly within the provided path are evaluated.
.PARAMETER RemoveEmptyDirectories
After removing old files, also remove any directories that are now empty.
This is done recursively from the deepest level up.
.PARAMETER Force
Forces removal of read-only and hidden files. Without this switch, read-only and
hidden files are skipped.
.PARAMETER WhatIf
Shows what files would be removed without actually removing anything.
.PARAMETER Confirm
Prompts for confirmation before removing files.
.EXAMPLE
PS > Remove-OldFile -OlderThan 30
Removes files in the current directory older than 30 days.
.EXAMPLE
PS > Remove-OldFile -Path C:\Logs -OlderThan 7 -Include '*.log','*.txt' -Recurse
Removes .log and .txt files from C:\Logs and subdirectories that are older than 7 days.
.EXAMPLE
PS > Remove-OldFile -OlderThan 12 -Unit Hours -RemoveEmptyDirectories
Removes files older than 12 hours and cleans up any empty directories.
.EXAMPLE
PS > Remove-OldFile -OlderThan 3 -Unit Months -Exclude '*.keep' -WhatIf
Shows what files older than 3 months would be removed, excluding files matching '*.keep'.
.EXAMPLE
PS > Remove-OldFile -Path ~/Downloads -OlderThan 90 -ExcludeDirectory @('Important', 'Archive')
Removes files older than 90 days from ~/Downloads, excluding the Important and Archive directories.
.EXAMPLE
PS > Remove-OldFile -OlderThan 1 -Unit Years -Force -Confirm
Removes files older than 1 year, including read-only and hidden files, with confirmation prompts.
.EXAMPLE
PS > Get-ChildItem -Directory | Remove-OldFile -OlderThan 14 -Include '*.tmp','*.cache'
Processes multiple directories via pipeline, removing .tmp and .cache files older than 14 days.
.OUTPUTS
[PSCustomObject]
Returns an object with summary information about the operation:
- FilesRemoved: Number of files successfully removed
- DirectoriesRemoved: Number of empty directories removed (if -RemoveEmptyDirectories specified)
- TotalSpaceFreed: Total disk space freed in bytes
- Errors: Number of errors encountered
- OldestDate: The cutoff date used for file age comparison
.NOTES
- Requires PowerShell 5.1 or later
- Uses LastWriteTime to determine file age
- Respects -WhatIf and -Confirm parameters for safety
- Read-only and hidden files are skipped unless -Force is specified
- Empty directory removal is performed after file removal and processes from deepest to shallowest
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/Remove-OldFile.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/Remove-OldFile.ps1
.LINK
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-item
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([PSCustomObject])]
param(
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[String]$Path = (Get-Location).Path,
[Parameter(Mandatory)]
[ValidateRange(1, [Int32]::MaxValue)]
[Int32]$OlderThan,
[Parameter()]
[ValidateSet('Days', 'Hours', 'Months', 'Years')]
[String]$Unit = 'Days',
[Parameter()]
[ValidateNotNullOrEmpty()]
[String[]]$Include,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String[]]$Exclude,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String[]]$ExcludeDirectory,
[Parameter()]
[Switch]$Recurse,
[Parameter()]
[Switch]$RemoveEmptyDirectories,
[Parameter()]
[Switch]$Force
)
begin
{
# Helper function to format file sizes
function Format-FileSize
{
param([Int64]$Size)
if ($Size -gt 1TB)
{
return '{0:N2} TB' -f ($Size / 1TB)
}
elseif ($Size -gt 1GB)
{
return '{0:N2} GB' -f ($Size / 1GB)
}
elseif ($Size -gt 1MB)
{
return '{0:N2} MB' -f ($Size / 1MB)
}
elseif ($Size -gt 1KB)
{
return '{0:N2} KB' -f ($Size / 1KB)
}
else
{
return '{0} bytes' -f $Size
}
}
function Test-IsExcludedDirectoryPath
{
param(
[String]$FilePath,
[String[]]$DirectoryPatterns
)
if (-not $DirectoryPatterns -or $DirectoryPatterns.Count -eq 0)
{
return $false
}
$directoryPath = [System.IO.Path]::GetDirectoryName($FilePath)
if ([String]::IsNullOrEmpty($directoryPath))
{
return $false
}
$pathSegments = $directoryPath -split '[\\/]'
foreach ($segment in $pathSegments)
{
if ([String]::IsNullOrWhiteSpace($segment))
{
continue
}
foreach ($pattern in $DirectoryPatterns)
{
if ($segment -like $pattern)
{
return $true
}
}
}
return $false
}
Write-Verbose 'Starting Remove-OldFile'
# Initialize counters
$filesRemoved = 0
$directoriesRemoved = 0
$totalSpaceFreed = 0
$errorCount = 0
# Calculate cutoff date
$cutoffDate = switch ($Unit)
{
'Hours' { (Get-Date).AddHours(-$OlderThan) }
'Days' { (Get-Date).AddDays(-$OlderThan) }
'Months' { (Get-Date).AddMonths(-$OlderThan) }
'Years' { (Get-Date).AddYears(-$OlderThan) }
}
Write-Verbose "Cutoff date: $($cutoffDate.ToString('yyyy-MM-dd HH:mm:ss'))"
Write-Verbose 'Files with LastWriteTime before this date will be removed'
# Collection to track processed directories for empty directory cleanup
$processedDirectories = [System.Collections.Generic.HashSet[String]]::new()
}
process
{
# Skip null or empty paths
if ([String]::IsNullOrWhiteSpace($Path))
{
Write-Verbose 'Skipping null or empty path'
continue
}
# Resolve path (handles ~, relative paths, etc.)
try
{
$resolvedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
# Ensure we got a valid path back
if ([String]::IsNullOrWhiteSpace($resolvedPath))
{
Write-Error "Failed to resolve path '$Path': resulted in empty path"
$errorCount++
continue
}
}
catch
{
Write-Error "Failed to resolve path '$Path': $($_.Exception.Message)"
$errorCount++
continue
}
# Verify path exists
if (-not (Test-Path -LiteralPath $resolvedPath))
{
Write-Error "Path not found: $resolvedPath"
$errorCount++
continue
}
Write-Verbose "Processing path: $resolvedPath"
# Build Get-ChildItem parameters
$getChildItemParams = @{
LiteralPath = $resolvedPath
File = $true
Recurse = $Recurse.IsPresent
Force = $Force
ErrorAction = 'SilentlyContinue'
}
# Get all files (wrap in array to ensure it's always an array)
$files = @(Get-ChildItem @getChildItemParams)
# Filter by Include patterns if specified (manual filtering for PS 5.1 compatibility)
if ($Include)
{
$files = $files | Where-Object {
$fileName = $_.Name
$matched = $false
foreach ($pattern in $Include)
{
if ($fileName -like $pattern)
{
$matched = $true
break
}
}
$matched
}
}
# Filter by Exclude patterns if specified (manual filtering for PS 5.1 compatibility)
if ($Exclude)
{
$files = $files | Where-Object {
$fileName = $_.Name
$excluded = $false
foreach ($pattern in $Exclude)
{
if ($fileName -like $pattern)
{
$excluded = $true
break
}
}
-not $excluded
}
}
# Filter by excluded directories if specified
if ($ExcludeDirectory)
{
$files = $files | Where-Object {
-not (Test-IsExcludedDirectoryPath -FilePath $_.FullName -DirectoryPatterns $ExcludeDirectory)
}
}
# Filter by age and process
foreach ($file in $files)
{
if ($file.LastWriteTime -lt $cutoffDate)
{
$fileSize = $file.Length
$fileName = $file.FullName
# Track parent directory for potential cleanup (before removal)
if ($RemoveEmptyDirectories)
{
$parentDir = [System.IO.Path]::GetDirectoryName($fileName)
if ($parentDir)
{
[void]$processedDirectories.Add($parentDir)
}
}
if ($PSCmdlet.ShouldProcess($fileName, 'Remove file'))
{
try
{
if ($Force)
{
Remove-Item -LiteralPath $fileName -Force -ErrorAction Stop
}
else
{
Remove-Item -LiteralPath $fileName -ErrorAction Stop
}
$filesRemoved++
$totalSpaceFreed += $fileSize
Write-Verbose "Removed: $fileName ($(Format-FileSize $fileSize))"
}
catch [System.UnauthorizedAccessException]
{
if ($Force)
{
Write-Error "Failed to remove file '$fileName': $($_.Exception.Message)"
$errorCount++
}
else
{
Write-Verbose "Skipping read-only or protected file: $fileName (use -Force to remove)"
}
}
catch [System.IO.IOException]
{
# On Unix systems, permission errors may manifest as IOException
if ($_.Exception.Message -match 'access rights|permission|read only')
{
if ($Force)
{
Write-Error "Failed to remove file '$fileName': $($_.Exception.Message)"
$errorCount++
}
else
{
Write-Verbose "Skipping read-only or protected file: $fileName (use -Force to remove)"
}
}
else
{
Write-Error "Failed to remove file '$fileName': $($_.Exception.Message)"
$errorCount++
}
}
catch
{
Write-Error "Failed to remove file '$fileName': $($_.Exception.Message)"
$errorCount++
}
}
}
}
}
end
{
# Remove empty directories if requested
if ($RemoveEmptyDirectories -and $processedDirectories.Count -gt 0)
{
Write-Verbose 'Checking for empty directories to remove...'
# Keep checking until no more directories can be removed
# This handles cascading empty directory removal (e.g., removing SubDir2 might make SubDir1 empty)
$removedInPass = $true
while ($removedInPass)
{
$removedInPass = $false
# Sort directories by depth (deepest first) to handle nested empty directories
$sortedDirs = $processedDirectories | Sort-Object { ($_ -split [regex]::Escape([System.IO.Path]::DirectorySeparatorChar)).Count } -Descending
foreach ($dir in $sortedDirs)
{
if (Test-Path -LiteralPath $dir)
{
try
{
# Check if directory is empty
$items = @(Get-ChildItem -LiteralPath $dir -Force -ErrorAction Stop)
if ($items.Count -eq 0)
{
if ($PSCmdlet.ShouldProcess($dir, 'Remove empty directory'))
{
Remove-Item -LiteralPath $dir -Force -ErrorAction Stop
$directoriesRemoved++
$removedInPass = $true
Write-Verbose "Removed empty directory: $dir"
# Track parent for potential cleanup
$parentDir = [System.IO.Path]::GetDirectoryName($dir)
if ($parentDir -and -not $processedDirectories.Contains($parentDir))
{
[void]$processedDirectories.Add($parentDir)
}
}
}
}
catch
{
Write-Verbose "Could not remove directory '$dir': $($_.Exception.Message)"
}
}
}
}
}
# Output summary
$summary = [PSCustomObject]@{
FilesRemoved = $filesRemoved
DirectoriesRemoved = $directoriesRemoved
TotalSpaceFreed = $totalSpaceFreed
TotalSpaceFreedMB = [Math]::Round($totalSpaceFreed / 1MB, 2)
Errors = $errorCount
OldestDate = $cutoffDate
}
Write-Verbose "Operation completed: $filesRemoved files removed, $directoriesRemoved directories removed"
Write-Verbose "Total space freed: $(Format-FileSize $totalSpaceFreed)"
return $summary
}
}