From 1bcc42793227440590576657a2f0b88ca7a5996f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 15:02:20 +0800 Subject: [PATCH] Add dedupe: find identical files by SHA-256 and move extra copies aside Claude-Session: https://claude.ai/code/session_01DU3cH5BSvNhkuGVHpNqpuF --- apps/dedupe.ps1 | 143 ++++++++++++++++++++++++++++++++++++++++ scripts/docgen-pages.py | 1 + 2 files changed, 144 insertions(+) create mode 100644 apps/dedupe.ps1 diff --git a/apps/dedupe.ps1 b/apps/dedupe.ps1 new file mode 100644 index 0000000..8796644 --- /dev/null +++ b/apps/dedupe.ps1 @@ -0,0 +1,143 @@ +# pwsh -File .\dedupe.ps1 +# Purpose: Find files with identical content (SHA-256) under a folder and optionally move the extra copies aside +# ============================================================================= +# Usage: +# powershell -ExecutionPolicy Bypass -File .\dedupe.ps1 -Path "" report only, changes nothing +# powershell -ExecutionPolicy Bypass -File .\dedupe.ps1 -Path "" -Move move extra copies to \_to_delete +# powershell -ExecutionPolicy Bypass -File .\dedupe.ps1 -Path "" -Report "" write the report to another file +# +# Output: +# Duplicates yyyyMMdd-HHmm.csv in Downloads: Set, Action (KEEP/DUPLICATE/MOVED), path, size, date, hash +# +# Note: +# Matches content only (size, then SHA-256 of the whole file); names and dates are ignored +# Keeper per set: a copy in a numbered top folder ("1. ...") first, then earliest modified, then shortest path +# -Move never deletes; it keeps the subfolder structure under _to_delete +# Skips hidden and system files, empty files and Office lock files (~$*) +# ============================================================================= + +param( + [Parameter(Mandatory = $true)][string]$Path, + [switch]$Move, + [string]$Report +) + +$ErrorActionPreference = 'Stop' + +# >>> say +function Say($msg, $color = 'Gray') { Write-Host $msg -ForegroundColor $color } +# <<< say + +# >>> downloads +function Get-DownloadsFolder { + $key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' + $raw = (Get-ItemProperty -Path $key -ErrorAction SilentlyContinue).'{374DE290-123F-4565-9164-39C4925E467B}' + if ($raw) { + $path = [Environment]::ExpandEnvironmentVariables($raw) + if (Test-Path -LiteralPath $path) { return $path } + } + return (Join-Path $env:USERPROFILE 'Downloads') +} +# <<< downloads + +if (-not (Test-Path -LiteralPath $Path -PathType Container -ErrorAction SilentlyContinue)) { + Say "Folder not found: $Path" Red + return +} +$root = (Resolve-Path -LiteralPath $Path).ProviderPath.TrimEnd('\') +$quarantine = Join-Path $root '_to_delete' +if (-not $Report) { + $name = Split-Path $root -Leaf + $Report = Join-Path (Get-DownloadsFolder) ('Duplicates {0} {1:yyyyMMdd-HHmm}.csv' -f $name, (Get-Date)) +} + +Say "Scanning $root ..." Cyan +$files = @(Get-ChildItem -LiteralPath $root -Recurse -File -ErrorAction SilentlyContinue | + Where-Object { + $_.Length -gt 0 -and + $_.Name -notlike '~$*' -and + $_.FullName -ne $Report -and + $_.FullName -notlike "$quarantine\*" + }) + +# Only files that share a size can be identical +$candidates = @($files | Group-Object Length | Where-Object { $_.Count -gt 1 } | ForEach-Object { $_.Group }) + +$total = $candidates.Count +$i = 0 +$hashed = foreach ($f in $candidates) { + $i++ + Write-Progress -Activity 'Hashing same-size files' -Status $f.Name -PercentComplete ([int](100 * $i / [math]::Max($total, 1))) + try { + [pscustomobject]@{ Hash = (Get-FileHash -LiteralPath $f.FullName -Algorithm SHA256).Hash; File = $f } + } catch { + Say "Could not read: $($f.FullName) - $($_.Exception.Message)" Yellow + } +} +Write-Progress -Activity 'Hashing same-size files' -Completed + +$groups = @($hashed | Group-Object Hash | Where-Object { $_.Count -gt 1 }) + +$rows = New-Object System.Collections.Generic.List[object] +$setNo = 0 +foreach ($g in $groups) { + $setNo++ + $ordered = @($g.Group | Sort-Object @{Expression = { + $top = $_.File.FullName.Substring($root.Length + 1).Split('\')[0] + if ($top -match '^\d+\.\s') { 0 } else { 1 } } }, + @{Expression = { $_.File.LastWriteTime } }, + @{Expression = { $_.File.FullName.Length } }, + @{Expression = { $_.File.FullName } }) + for ($k = 0; $k -lt $ordered.Count; $k++) { + $item = $ordered[$k] + $isKeeper = ($k -eq 0) + $rel = $item.File.FullName.Substring($root.Length + 1) + $action = if ($isKeeper) { 'KEEP' } else { 'DUPLICATE' } + $movedTo = '' + + if ($Move -and -not $isKeeper) { + try { + $dest = Join-Path $quarantine $rel + [System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($dest)) | Out-Null + $n = 1 + $base = $dest + while ([System.IO.File]::Exists($dest)) { + $dest = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($base), + [System.IO.Path]::GetFileNameWithoutExtension($base) + " ($n)" + [System.IO.Path]::GetExtension($base)) + $n++ + } + [System.IO.File]::Move($item.File.FullName, $dest) + $action = 'MOVED' + $movedTo = $dest + } catch { + $action = 'MOVE FAILED' + Say "Could not move: $($item.File.FullName) - $($_.Exception.Message)" Yellow + } + } + + $rows.Add([pscustomobject]@{ + Set = $setNo + Action = $action + RelativePath = $rel + SizeBytes = $item.File.Length + LastModified = $item.File.LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss') + SHA256 = $item.Hash + MovedTo = $movedTo + }) + } +} + +if ($rows.Count -eq 0) { + Say ("{0} files scanned. No duplicates found." -f $files.Count) Green + return +} + +$rows | Export-Csv -LiteralPath $Report -NoTypeInformation -Encoding UTF8 + +$extras = @($rows | Where-Object { $_.Action -ne 'KEEP' }) +$wastedMB = (($extras | Measure-Object SizeBytes -Sum).Sum) / 1MB +Say ("{0} files scanned, {1} duplicate sets, {2} extra copies ({3:N1} MB)." -f $files.Count, $setNo, $extras.Count, $wastedMB) Green +Say "Report: $Report" White +if (-not $Move) { + Say "Nothing was moved. Re-run with -Move to move the extra copies into $quarantine" Yellow +} diff --git a/scripts/docgen-pages.py b/scripts/docgen-pages.py index 53e69e3..89d5b44 100755 --- a/scripts/docgen-pages.py +++ b/scripts/docgen-pages.py @@ -24,6 +24,7 @@ 'agentprofiler': 'Agent Profiler', 'appupdate': 'App Update', 'checkenv': 'Check Env', + 'dedupe': 'Dedupe', 'displayswitch': 'Display Switch', 'extractfiles': 'Extract Files', 'filefind': 'File Find',