[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [int]$StaleDays = 7, [string]$CsvPath ) $ErrorActionPreference = 'Stop' $root = [System.IO.Path]::GetFullPath($Path) if (-not (Test-Path -LiteralPath $root -PathType Container)) { throw "Backup folder not found: $root" } if ($StaleDays -lt 1) { throw 'StaleDays must be positive.' } $items = @(Get-ChildItem -LiteralPath $root -Force -ErrorAction SilentlyContinue) if ($items.Count -eq 0) { Write-Host 'Backup folder is empty.' return } $rows = @() foreach ($item in $items) { $count = 0 $bytes = [int64]0 if ($item.PSIsContainer) { $children = Get-ChildItem -LiteralPath $item.FullName -Recurse -File -Force -ErrorAction SilentlyContinue foreach ($file in $children) { $count++ $bytes += $file.Length } } else { $count = 1 $bytes = $item.Length } $age = [math]::Floor(((Get-Date) - $item.LastWriteTime).TotalDays) $setName = $item.Name -replace '[-_.]?\d{8}([-_]?\d{6})?.*$', '' if ([string]::IsNullOrWhiteSpace($setName)) { $setName = $item.Name } $type = if ($item.PSIsContainer) { 'folder' } else { 'file' } $rows += [pscustomobject]@{ Set = $setName Name = $item.Name Type = $type LastWrite = $item.LastWriteTime AgeDays = $age Files = $count SizeGB = [math]::Round($bytes / 1GB, 2) Stale = ($age -gt $StaleDays) } } $rows | Sort-Object -Property Set, LastWrite -Descending | Format-Table -AutoSize $groups = $rows | Group-Object -Property Set foreach ($group in $groups) { $latest = $group.Group | Sort-Object -Property LastWrite -Descending | Select-Object -First 1 Write-Host ("{0}: copies {1}, latest {2}, age {3} days" -f $group.Name, $group.Count, $latest.Name, $latest.AgeDays) } $stale = @($rows | Where-Object { $_.Stale }) if ($stale.Count -gt 0) { Write-Warning ("Stale copies: {0}" -f $stale.Count) } if (-not [string]::IsNullOrWhiteSpace($CsvPath)) { $csvFull = [System.IO.Path]::GetFullPath($CsvPath) if (Test-Path -LiteralPath $csvFull) { throw "CSV already exists: $csvFull" } $rows | Sort-Object -Property Set, LastWrite -Descending | Export-Csv -LiteralPath $csvFull -NoTypeInformation -Encoding UTF8 Write-Host "CSV: $csvFull" }