Hashing is the easy part. Hard links, sparse files, and a race condition that silently poisons your results are not.

Every "free up 50 GB" utility makes duplicate detection sound like a solved problem. Walk the filesystem, group by size, hash what's left, delete the extras. Three steps, one afternoon.

It is not three steps. I spent a week building one of these scanners properly, and almost none of that time went into hashing. It went into the things NTFS does that a naive implementation gets wrong — and two of those failure modes are the kind that report success while being completely incorrect.

This is what I hit, in the order I hit it.

The premise is wrong before you write a line of code

Windows has no duplicate file finder. Storage Sense is the closest built-in feature, and it explicitly does not look for duplicate content — it clears temp files, previous Windows installations, delivery optimization caches, and Recycle Bin contents on a schedule.

So the scanner is yours to write. Here is where it breaks.

Trap 1: "Size" is a lie you tell yourself

The obvious first pass is to bucket files by size. Two files with different sizes cannot be identical, so you only hash within size buckets. That is correct logic and it is built on a number that does not mean what you think it means.

Get-ChildItem returns Length, the logical size — the number of bytes the file's content would occupy if written out in full. What you actually reclaim when you delete a file is the allocated size on disk, and on NTFS those two numbers diverge in both directions.

A sparse file is the extreme case. Hyper-V and VirtualBox write multi-gigabyte virtual disk images where most of the file is zeroes, and NTFS does not allocate clusters for the zero ranges. A 40 GB .vhdx can occupy 900 MB on disk. Delete it and you free 900 MB. Your scanner, working from Length, just told the user it would recover 40 GB.

The reverse also happens. A directory full of 1 KB files each occupies a full 4 KB cluster, so 10,000 files that Length reports as 10 MB are consuming 40 MB. Compression (compact /c) and NTFS file compression push the ratio the other way again.

You can query the truth:

fsutil sparse queryflag "D:\VMs\lab.vhdx" fsutil file layout "D:\VMs\lab.vhdx" 

fsutil file layout reports both logical and allocated size, plus the set of data streams. If your tool shows a "recoverable space" number computed from Length, that number is fiction on any machine with VMs, databases, or compressed folders.

This one is worse, because it is not rare. It is how Windows ships.

C:\Windows\WinSxS is built almost entirely on hard links. So is every Docker image layer on a Windows host, and so are most modern installers that ship both an x86 and x64 binary sharing resources. A hard link is a second directory entry pointing at the same file record — same data, same file ID, two names. Per Microsoft's documentation, deleting one name does not delete the data; the clusters are freed only when the last link is gone.

A scanner that walks paths sees two files with identical content and identical size. It groups them. It offers to delete one. It reports the size back as recoverable. Deleting it frees nothing — the data is still there under the other name.

On a Windows 11 install with the component store intact, I have seen naive scanners report tens of gigabytes of "recoverable" duplicate data that was almost entirely hard links. The number was not slightly off. It was meaningless.

The fix is to stop treating paths as file identity. Two paths are the same file if they resolve to the same file ID on the same volume:

fsutil file queryfileid "C:\Windows\System32\kernel32.dll" fsutil hardlink list "C:\Windows\System32\kernel32.dll" 

queryfileid returns the 64-bit NTFS file ID. hardlink list returns every path pointing at that record. If a duplicate group's members share a file ID, the group is a hard link set — skip it, report zero recoverable bytes, and move on.

Programmatically the clean route is GetFileInformationByHandleEx with the FileIdInfo class, which gives you a FILE_ID_INFO structure containing the volume serial number and a 128-bit file ID. That 128-bit form is what you want if you are also handling ReFS, where 64-bit IDs are not guaranteed unique across volumes.

Trap 3: Junctions turn recursion into an infinite hallway

C:\Users\\Application Data is not a folder. It is a junction pointing at AppData\Roaming. And AppData\Local\Application Data points back up the tree. These exist for compatibility with pre-Vista software and they have been shipping since 2007.

Whether your recursion walks into them depends on your toolchain and version. When it does, you get paths like C:\Users\me\AppData\Local\Application Data\Application Data\Application Data\... growing until something gives out — either MAX_PATH, or your patience, or the stack.

Defend with an explicit depth cap and a visited-set keyed on file ID (not path, since the path is different every time you loop):

$visited = [System.Collections.Generic.HashSet[string]]::new() Get-ChildItem -LiteralPath $root -Directory -Recurse -Depth 32 -ErrorAction SilentlyContinue | Where-Object { -not $_.Attributes.ToString().Contains('ReparsePoint') } 

-Depth exists in PowerShell 5.1 and later and is the cheapest guard you can add. Skipping anything with the ReparsePoint attribute handles junctions and symlinks in one filter.

Trap 4: The race condition that silently corrupts your results

This is the one nobody writes about, and it is the one that will get you blamed for data loss.

A scan is not atomic. You enumerate sizes at 10:00:00, you finish hashing at 10:04:30. In those four and a half minutes, a browser finishes downloading a file, a game patches itself, an editor autosaves. Any of those can change a file's content or size mid-scan.

Three distinct failure modes come out of this:

False negative. File A and File B were identical when you enumerated them, but A grew by 40 MB before you hashed it. They no longer match, so you miss a real duplicate. Annoying, not dangerous.

False positive. File A and File B hash to the same value because you read both at a moment when they happened to be identical — say, two copies of a file being written by the same sync client. By the time the user clicks delete, they have diverged. You just deleted a file that was no longer a duplicate.

The truncated read. You open a file that is actively being written, read to the length you recorded earlier, and hash a prefix of a file that is now longer. The hash matches a shorter file exactly. This is the worst one, because the result looks perfectly valid.

The fix is to treat every hash as a claim that must be re-verified at deletion time:

$before = Get-Item -LiteralPath $path $hash = (Get-FileHash -LiteralPath $path -Algorithm MD5).Hash $after = Get-Item -LiteralPath $path if ($before.Length -ne $after.Length -or $before.LastWriteTimeUtc -ne $after.LastWriteTimeUtc) { # file changed while hashing — discard this result } 

And when opening for the prefix read, open with FileShare.ReadWrite so you do not block the writer, but check $fs.Length again after opening rather than trusting the value from enumeration.

A scanner that skips this check will work flawlessly on a quiet test folder and produce a wrong answer on a real machine.

Trap 5: Empty files, and files smaller than your prefix

Two edge cases that make your results look ridiculous.

Every zero-byte file hashes to the same value. Enumerate a developer's home directory and you will find hundreds of them — .gitkeep, placeholder configs, lock files, __init__.py. A naive scanner groups all of them into one enormous "duplicate group" and reports a recoverable size of 0 bytes, which is technically true and completely useless as a UI.

Filter Length -eq 0 out at the enumeration stage. There is nothing to recover and nothing to decide.

The second case is subtler. The standard optimization is to hash only the first 4 KB before committing to a full read. For any file at or under 4 KB, the prefix hash is the full hash — so you read the same bytes twice and compute the same digest twice. Not wrong, just wasteful. Special-case files where Length -le $prefixBytes and promote the prefix hash straight to a confirmed hash.

The funnel, in the right order

The whole design is a cost gradient. Each stage is more expensive per file than the last, and each stage shrinks the candidate set by an order of magnitude.

Stage 1 — enumerate. One stat per file. Collect path, logical size, allocated size, last write time, attributes. Do not open any file. On 500,000 files this is the slow part and there is no way around it short of reading the MFT directly.

Stage 2 — bucket by size. Discard every singleton. On a typical user profile this eliminates 85–95% of files before you have read a single byte of content. Zero-byte files die here too.

Stage 3 — prefix hash. Within each size bucket, open each file and read the first 4 KB. The cost is one open plus one small read per candidate. This is where the real work happens: two files sharing a size but differing in content almost always differ in the first few kilobytes, because file formats put headers and metadata up front.

Stage 4 — full hash. Only files that survived the prefix hash get read end to end. On a real machine this is a handful of files, not thousands.

Stage 5 — verify before delete. Re-stat, compare size and mtime against what you recorded, and refuse to act if anything moved.

The ordering is not a micro-optimization. Getting it wrong — hashing everything up front, for instance — turns a four-minute scan into a four-hour one, and on a spinning disk into something worse.

Choosing the hash

MD5 is the right default and people will argue with you about it.

MD5 is cryptographically broken. Chosen-prefix collisions are cheap to construct, and if an attacker controls one of the files, they can make two different files hash identically (RFC 1321 describes the algorithm; the breaks came later). That is a real problem for signatures. It is not a problem here, because the threat model is accidental collision, not adversarial.

The accidental collision math: for n files drawn from a 2^128 space, the birthday bound gives roughly n² / 2^129. At one million files that is about 1.5 × 10^-27. You will not see it. You will not see it if every human on earth runs the scan every day for the lifetime of the universe.

What matters more is throughput. Get-FileHash -Algorithm MD5 runs at a few hundred MB/s on a modern CPU with hardware acceleration. SHA-256 is meaningfully slower for zero additional safety in this threat model. If you are hashing terabytes, a non-cryptographic hash like xxHash64 or BLAKE3 in its fastest mode will beat both by a wide margin, and collision resistance is still far beyond what you need.

The real correctness risk in this system is not the hash function. It is Trap 4.

What this still cannot do

Being honest about the boundary, because the "50 GB in one click" apps are not:

Near-duplicates are a different problem. A photo resized to 50% has a completely different hash. So does a video re-encoded at a lower bitrate. Finding those requires perceptual hashing — pHash, dHash, or an embedding index — and the output is a similarity score, not a boolean. Do not let a tool conflate the two; "duplicate" and "similar" have different deletion risk.

Compressed and deduplicated volumes change the accounting. On ReFS with block cloning enabled, two files can share physical clusters without being hard links, and deleting one does free space — just not the amount the logical size suggests. On NTFS with compression, the same applies. If you are reporting a recoverable-bytes number, it has to come from allocated size and link count, not Length.

System files are not yours to touch. WinSxS, System Volume Information, and the hibernation file are all either hard-link farms or managed by servicing. Exclude them at the root.

The short version

Enumerate once. Bucket by size and throw away singletons. Hash a 4 KB prefix, then hash in full only what survives. Deduplicate by file ID, not path, so hard links do not inflate your numbers. Cap recursion depth and skip reparse points. Re-stat before you delete anything, because the filesystem moved while you were reading it. Send deletions to the Recycle Bin, never to Delete().

None of that is hashing. All of it is what determines whether your scan result is true.

I wrote one of these scanners — FileDedupe — so I have a bias here. It is free, it does the file-ID and allocated-size accounting described above, and it deletes to the Recycle Bin by default. The PowerShell in this article is enough to build your own if you would rather.