Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions apps/dedupe.ps1
Original file line number Diff line number Diff line change
@@ -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 "<folder>" report only, changes nothing
# powershell -ExecutionPolicy Bypass -File .\dedupe.ps1 -Path "<folder>" -Move move extra copies to <folder>\_to_delete
# powershell -ExecutionPolicy Bypass -File .\dedupe.ps1 -Path "<folder>" -Report "<file.csv>" write the report to another file
#
# Output:
# Duplicates <Folder> 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
}
1 change: 1 addition & 0 deletions scripts/docgen-pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
'agentprofiler': 'Agent Profiler',
'appupdate': 'App Update',
'checkenv': 'Check Env',
'dedupe': 'Dedupe',
'displayswitch': 'Display Switch',
'extractfiles': 'Extract Files',
'filefind': 'File Find',
Expand Down
Loading