1function Get-FileAudit {
2 param(
3 [Parameter(Mandatory)]
4 [string]$Path,
5 [int]$DaysOld = 30,
6 [string[]]$Extension = @("*")
7 )
8
9 $cutoff = (Get-Date).AddDays(-$DaysOld)
10
11 Get-ChildItem -Path $Path -Recurse -File |
12 Where-Object {
13 $ext = $_.Extension.TrimStart(".")
14 ($Extension -contains "*") -or
15 ($Extension -contains $ext)
16 } |
17 Select-Object @{
18 Name = "RelativePath"
19 Expression = {
20 $_.FullName.Replace($Path, ".")
21 }
22 }, @{
23 Name = "SizeKB"
24 Expression = {
25 [math]::Round($_.Length / 1KB, 2)
26 }
27 }, LastWriteTime, Extension |
28 Sort-Object SizeKB -Descending
29}
30
31function Get-DuplicateFiles {
32 param(
33 [Parameter(Mandatory)]
34 [string]$Path
35 )
36
37 $hashes = @{}
38 Get-ChildItem -Path $Path -Recurse -File |
39 ForEach-Object {
40 $hash = (Get-FileHash $_.FullName -Algorithm MD5).Hash
41 if ($hashes.ContainsKey($hash)) {
42 $hashes[$hash] += @($_.FullName)
43 } else {
44 $hashes[$hash] = @($_.FullName)
45 }
46 }
47
48 $hashes.GetEnumerator() |
49 Where-Object { $_.Value.Count -gt 1 } |
50 ForEach-Object {
51 [PSCustomObject]@{
52 Hash = $_.Key
53 Count = $_.Value.Count
54 Files = $_.Value
55 Size = (Get-Item $_.Value[0]).Length
56 }
57 } |
58 Sort-Object Size -Descending
59}
60
61function Compress-OldFiles {
62 param(
63 [Parameter(Mandatory)]
64 [string]$Path,
65 [int]$DaysOld = 90,
66 [string]$ArchivePath
67 )
68
69 $oldFiles = Get-FileAudit -Path $Path -DaysOld $DaysOld
70 $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
71 $zipPath = Join-Path $ArchivePath "archive_$timestamp.zip"
72
73 $oldFiles |
74 Select-Object -ExpandProperty RelativePath |
75 Compress-Archive -DestinationPath $zipPath
76
77 [PSCustomObject]@{
78 Archive = $zipPath
79 FileCount = $oldFiles.Count
80 TotalSizeKB = ($oldFiles | Measure-Object SizeKB -Sum).Sum
81 }
82}