Find Duplicate Files with PowerShell: Free GUI, Works Across Folders

Advertisement
Find duplicate files with PowerShell, no install File Operations
Advertisement

Our team share was running out of space, and when I looked inside, the same quotes and photos were sitting in several places under different names. Free duplicate finders are everywhere, but a work PC usually will not let you install them.

So I wrote a small duplicate file finder with a window, using nothing but the PowerShell that ships with Windows. Add a folder and click Scan. It lists files whose content is identical, even if their names are not. It also picks one file in each group to keep.

  • It works on a single folder, or across two or more folders, such as your own Documents and a team share
  • It hashes only files that share a size with another file, so it is much faster than hashing everything (a quarter to a third of the time in my 4,000-file test)
  • Instead of deleting, it moves the extra copies to a holding folder and writes a log, so you can put everything back later
The Duplicate File Finder window. Two folders are listed at the top, with groups of identical files below it. The file to keep in each group is in bold
Scanning a Documents folder and a team share. Files with different names land in the same group when their content matches

What counts as a duplicate file?

Here a duplicate means a file whose content matches another file byte for byte, whatever its name or location. At work they pile up like this:

  • Quote - Copy.xlsx, made by copying a file in File Explorer
  • IMG_0012 (1).JPG, the same attachment saved twice from email or Teams
  • A proposal you renamed to something like [SENT] or _final and also put on the team share

Because the names vary, sorting by name or size in File Explorer rarely gives them away. The reliable test is to compare hash values. A hash is a long string calculated from the file content, and it changes completely if even one byte differs. I covered how to get one in my Get-FileHash guide.

Comparing two folders to see what changed is a different job: there you compare files with the same name in the same place. For checking a backup or a before-and-after copy, see how to compare two folders by hash.

How to use it

Save the script at the end of this post and run it. The window opens right away. You do not need admin rights or any extra software. For this walkthrough I set up a Documents folder and a team share with these files in them.

File Explorer showing the My-Documents folder with a quote, a copy of it, a proposal, meeting minutes, monthly reports and more
My side. Quote_ClientA_2026-11 - Copy.xlsx was made with copy and paste in File Explorer
File Explorer showing the Shared-Sales folder with a sent quote, a final proposal, meeting minutes and more
The team share. Some files here have different names but the same content as files on my side

My Windows is set to Japanese, so the File Explorer column headers in these screenshots are in Japanese. The tool itself is in English.

Step 1: Add the folders to scan

Click Add folder, or drag folders from File Explorer onto the list. With two folders or more, it also finds duplicates across them. A folder higher in the list counts as the original, so its copy is the one kept by default. Use Up and Down to change the order.

If you check the same folders every month, click Save current settings as and give the set a name. Next time, just pick it from Saved sets. There is nothing to edit inside the script.

Step 2: Click Scan

The window stays responsive during the scan, with a progress bar and a Stop button if you change your mind. When it finishes, identical files appear in groups, with the groups that free the most space at the top.

In the example, it found 5 groups (12 files) among 18 files. [SENT] Quote_ClientA.xlsx and Booth_front.JPG have different names but the same content, so they joined their groups. Monthly-report_Oct.xlsx and Monthly-report_Nov.xlsx have exactly the same size, yet they do not show up, because their content differs.

Step 3: Check which file is kept

In each group, one row is unchecked and shown in bold. That is the file to keep. You choose the rule under File to keep.

File to keep When to use it
The one in the folder higher in the list (default) You know which location is the master, such as your PC versus the team share
The shortest path Clearing out - Copy files inside one folder
The oldest modified date You want to keep the first version
The newest modified date You want to keep the last saved version

You can tick or untick rows yourself. If you try to tick every file in a group, the tool stops you, because that would leave no copy at all. Double-click a row to open its location in File Explorer.

Step 4: Save a CSV, or move the copies

If you need sign-off before cleaning up, click Save results as CSV. The file is UTF-8 with a BOM, so Excel opens it cleanly. It also includes full paths and hash values.

When you are ready, click Move checked files to a holding folder and choose a location. The tool creates a duplicates_moved_<date> folder there and moves the files into it, keeping the original folder structure. Files changed since the scan are skipped.

The tool after the move. No duplicates remain, and the number of moved files and the holding folder are shown
Seven files (14.1 MB) moved. Moved files disappear from the list
File Explorer showing the holding folder, split by scanned folder, with the moved files and move-log.csv
Inside the holding folder: one subfolder per scanned folder, such as 1_My-Documents and 2_Shared-Sales

Step 5: Undo if needed

The holding folder contains move-log.csv. Click Undo a move, choose that file, and every file goes back where it was. If a file with the same name already exists in the original spot, it is skipped, never overwritten. Once nobody has missed anything for a while, delete the holding folder.

In my test, restored files matched the originals in name, size, modified time and hash.

Why not just sort in File Explorer, or hash everything?

Sorting by size in File Explorer works for a handful of files. But copies with different names are easy to miss, and you cannot tell real duplicates from files that just happen to share a size, like the two monthly reports above.

If you know PowerShell, a few lines that pipe every file into Get-FileHash then group by hash will find the same groups. The difference is speed. Files of different sizes can never be identical, so this tool hashes only files that share a size. That is the only data it reads in full.

Here is a test on 4,000 files (about 2 GB), where one in ten was a renamed copy. Every method found the same 344 groups.

Method Windows PowerShell 5.1 PowerShell 7
Hash every file (SHA256) 14.6 s 8.3 s
Hash every file (MD5, the approach of my 2020 version) 12.7 s 6.5 s
Hash only same-size files (SHA256, this tool) 3.3 s 3.0 s

Times are the average of two runs. The tool hashed only 780 of the 4,000 files, or 383 MB, so it read about a fifth of the data.

The other difference is the cleanup. With a quick script, deciding what to keep and deleting the rest is up to you, along with the risk of deleting every copy by mistake. This tool never moves a whole group and never deletes anything, so you can always undo.

The script (full code)

Save the script below as duplicate-finder.ps1 (any name works), then run it with PowerShell. If you have never run PowerShell code before, see how to run PowerShell code you copied.

I tested it on Windows 11 with both Windows PowerShell 5.1 and PowerShell 7. Feel free to use it.

# Duplicate File Finder (en-duplicate-finder.ps1)
# Finds files with identical content in one or more folders, without installing anything.
# It hashes (SHA256) only files that share a size with another file, so it reads far less than hashing everything.
# It picks one file to keep per group, can move the rest to a holding folder, then undo that move from its log.
# Tested on Windows PowerShell 5.1 / PowerShell 7.
Add-Type -AssemblyName System.Windows.Forms, System.Drawing, Microsoft.VisualBasic
[System.Windows.Forms.Application]::EnableVisualStyles()

$SetFile = Join-Path $env:APPDATA 'duplicate-file-finder-en.json'
$KeepRules = @(
    'The one in the folder higher in the list (then the shortest path)',
    'The shortest path (the one without - Copy in its name)',
    'The oldest modified date',
    'The newest modified date'
)

function Format-Size([double]$b) {
    # Round the same way on 5.1 and 7
    if ($b -ge 1GB) { return '{0:N2} GB' -f [Math]::Round($b / 1GB, 2, [MidpointRounding]::AwayFromZero) }
    if ($b -ge 1MB) { return '{0:N1} MB' -f [Math]::Round($b / 1MB, 1, [MidpointRounding]::AwayFromZero) }
    if ($b -ge 1KB) { return '{0:N0} KB' -f ($b / 1KB) }
    return '{0:N0} B' -f $b
}
function Show-Msg($text, $buttons = 'OK', $icon = 'Information') {
    return [System.Windows.Forms.MessageBox]::Show($text, 'Duplicate File Finder', $buttons, $icon)
}

# ---------- Window ----------
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Duplicate File Finder'
$form.Size = New-Object System.Drawing.Size(1100, 760)
$form.MinimumSize = New-Object System.Drawing.Size(900, 600)
$form.StartPosition = 'CenterScreen'
$form.Font = New-Object System.Drawing.Font('Segoe UI', 9)

$top = New-Object System.Windows.Forms.Panel
$top.Dock = 'Top'; $top.Height = 205
$form.Controls.Add($top)

$lblFolders = New-Object System.Windows.Forms.Label
$lblFolders.Text = 'Folders to scan (you can drag folders here too; with two folders or more, it also finds duplicates across them)'
$lblFolders.Location = New-Object System.Drawing.Point(10, 8); $lblFolders.AutoSize = $true
$top.Controls.Add($lblFolders)

$lstFolders = New-Object System.Windows.Forms.ListBox
$lstFolders.Location = New-Object System.Drawing.Point(10, 28)
$lstFolders.Size = New-Object System.Drawing.Size(860, 84)
$lstFolders.Anchor = 'Top, Left, Right'
$lstFolders.AllowDrop = $true
$lstFolders.HorizontalScrollbar = $true
$top.Controls.Add($lstFolders)

function New-Button($text, $x, $y, $w, $parent) {
    $b = New-Object System.Windows.Forms.Button
    $b.Text = $text; $b.Location = New-Object System.Drawing.Point($x, $y)
    $b.Size = New-Object System.Drawing.Size($w, 26); $parent.Controls.Add($b); return $b
}
$btnAdd = New-Button 'Add folder...' 880 28 190 $top
$btnRemove = New-Button 'Remove folder' 880 58 190 $top
$btnUp = New-Button 'Up' 880 88 92 $top
$btnDown = New-Button 'Down' 978 88 92 $top
foreach ($b in $btnAdd, $btnRemove, $btnUp, $btnDown) { $b.Anchor = 'Top, Right' }

$lblSet = New-Object System.Windows.Forms.Label
$lblSet.Text = 'Saved sets:'; $lblSet.AutoSize = $true
$lblSet.Location = New-Object System.Drawing.Point(10, 122)
$top.Controls.Add($lblSet)
$cmbSet = New-Object System.Windows.Forms.ComboBox
$cmbSet.DropDownStyle = 'DropDownList'
$cmbSet.Location = New-Object System.Drawing.Point(130, 118); $cmbSet.Size = New-Object System.Drawing.Size(260, 24)
$top.Controls.Add($cmbSet)
$btnSetSave = New-Button 'Save current settings as...' 400 117 210 $top
$btnSetDel = New-Button 'Delete this set' 620 117 160 $top

$chkZero = New-Object System.Windows.Forms.CheckBox
$chkZero.Text = 'Skip 0-byte files'; $chkZero.Checked = $true; $chkZero.AutoSize = $true
$chkZero.Location = New-Object System.Drawing.Point(10, 150)
$top.Controls.Add($chkZero)
$chkHidden = New-Object System.Windows.Forms.CheckBox
$chkHidden.Text = 'Include hidden or system files'; $chkHidden.AutoSize = $true
$chkHidden.Location = New-Object System.Drawing.Point(200, 150)
$top.Controls.Add($chkHidden)
$lblKeep = New-Object System.Windows.Forms.Label
$lblKeep.Text = 'File to keep:'; $lblKeep.AutoSize = $true
$lblKeep.Location = New-Object System.Drawing.Point(470, 152)
$top.Controls.Add($lblKeep)
$cmbKeep = New-Object System.Windows.Forms.ComboBox
$cmbKeep.DropDownStyle = 'DropDownList'
$cmbKeep.Location = New-Object System.Drawing.Point(560, 148); $cmbKeep.Size = New-Object System.Drawing.Size(390, 24)
[void]$cmbKeep.Items.AddRange($KeepRules); $cmbKeep.SelectedIndex = 0
$top.Controls.Add($cmbKeep)

$btnScan = New-Button 'Scan' 10 175 120 $top
$btnScan.Font = New-Object System.Drawing.Font('Segoe UI', 9, [System.Drawing.FontStyle]::Bold)
$btnCancel = New-Button 'Stop' 140 175 80 $top
$btnCancel.Enabled = $false
$progress = New-Object System.Windows.Forms.ProgressBar
$progress.Location = New-Object System.Drawing.Point(230, 178); $progress.Size = New-Object System.Drawing.Size(240, 20)
$top.Controls.Add($progress)
$lblStatus = New-Object System.Windows.Forms.Label
$lblStatus.Location = New-Object System.Drawing.Point(480, 180); $lblStatus.Size = New-Object System.Drawing.Size(590, 20)
$lblStatus.Anchor = 'Top, Left, Right'; $lblStatus.AutoEllipsis = $true
$top.Controls.Add($lblStatus)

$bottom = New-Object System.Windows.Forms.Panel
$bottom.Dock = 'Bottom'; $bottom.Height = 70
$form.Controls.Add($bottom)
$lblSum = New-Object System.Windows.Forms.Label
$lblSum.Location = New-Object System.Drawing.Point(10, 6); $lblSum.Size = New-Object System.Drawing.Size(1060, 20)
$lblSum.Anchor = 'Top, Left, Right'
$bottom.Controls.Add($lblSum)
$btnCsv = New-Button 'Save results as CSV...' 10 34 170 $bottom
$btnMove = New-Button 'Move checked files to a holding folder...' 190 34 300 $bottom
$btnUndo = New-Button 'Undo a move...' 500 34 220 $bottom
$btnErrors = New-Button 'Unreadable files' 730 34 170 $bottom
foreach ($b in $btnCsv, $btnMove, $btnErrors) { $b.Enabled = $false }

$grid = New-Object System.Windows.Forms.DataGridView
$grid.Dock = 'Fill'
$grid.AllowUserToAddRows = $false; $grid.AllowUserToDeleteRows = $false
$grid.RowHeadersVisible = $false; $grid.SelectionMode = 'FullRowSelect'
$grid.AutoSizeColumnsMode = 'None'
$form.Controls.Add($grid); $grid.BringToFront()

$table = New-Object System.Data.DataTable
foreach ($c in @(
        @('Move', [bool]), @('Group', [int]), @('Name', [string]), @('Location', [string]),
        @('Size', [string]), @('Modified', [datetime]), @('Root', [int]),
        @('FullName', [string]), @('Bytes', [long]), @('Hash', [string]))) {
    [void]$table.Columns.Add($c[0], $c[1])
}
$grid.DataSource = $table

function Set-GridLook {
    foreach ($col in $grid.Columns) { $col.SortMode = 'NotSortable'; $col.ReadOnly = ($col.Name -ne 'Move') }
    foreach ($n in 'FullName', 'Bytes', 'Hash') { $grid.Columns[$n].Visible = $false }
    $w = @{ 'Move' = 50; 'Group' = 50; 'Name' = 280; 'Location' = 300; 'Size' = 85; 'Modified' = 140; 'Root' = 60 }
    foreach ($k in $w.Keys) { $grid.Columns[$k].Width = $w[$k] }
    $grid.Columns['Modified'].DefaultCellStyle.Format = 'yyyy-MM-dd HH:mm'
    $grid.Columns['Size'].DefaultCellStyle.Alignment = 'MiddleRight'
    $grid.Columns['Root'].HeaderText = 'Folder #'
    $grid.Columns['Root'].Width = 70
    $grid.Columns['Location'].AutoSizeMode = 'Fill'
}

# Alternate the background per group. The file to keep is shown in bold
$boldFont = New-Object System.Drawing.Font('Segoe UI', 9, [System.Drawing.FontStyle]::Bold)
$grid.Add_CellFormatting({
        param($s, $e)
        $row = $grid.Rows[$e.RowIndex]
        $g = [int]$row.Cells['Group'].Value
        $e.CellStyle.BackColor = if ($g % 2 -eq 0) { [System.Drawing.Color]::FromArgb(235, 243, 255) } else { [System.Drawing.Color]::White }
        if (-not [bool]$row.Cells['Move'].Value) { $e.CellStyle.Font = $boldFont }
    })

# ---------- Folder list ----------
function Add-Folder([string]$path) {
    if (-not (Test-Path -LiteralPath $path -PathType Container)) { return }
    $full = (Get-Item -LiteralPath $path).FullName
    foreach ($f in $lstFolders.Items) { if ($f -eq $full) { return } }
    [void]$lstFolders.Items.Add($full)
}
$btnAdd.Add_Click({
        $dlg = New-Object System.Windows.Forms.FolderBrowserDialog
        $dlg.Description = 'Choose a folder to scan'
        if ($dlg.ShowDialog() -eq 'OK') { Add-Folder $dlg.SelectedPath }
    })
$btnRemove.Add_Click({ if ($lstFolders.SelectedIndex -ge 0) { $lstFolders.Items.RemoveAt($lstFolders.SelectedIndex) } })
function Move-Folder([int]$d) {
    $i = $lstFolders.SelectedIndex; $j = $i + $d
    if ($i -lt 0 -or $j -lt 0 -or $j -ge $lstFolders.Items.Count) { return }
    $v = $lstFolders.Items[$i]; $lstFolders.Items.RemoveAt($i); $lstFolders.Items.Insert($j, $v); $lstFolders.SelectedIndex = $j
}
$btnUp.Add_Click({ Move-Folder -1 })
$btnDown.Add_Click({ Move-Folder 1 })
$lstFolders.Add_DragEnter({ param($s, $e) if ($e.Data.GetDataPresent([System.Windows.Forms.DataFormats]::FileDrop)) { $e.Effect = 'Copy' } })
$lstFolders.Add_DragDrop({
        param($s, $e)
        foreach ($p in $e.Data.GetData([System.Windows.Forms.DataFormats]::FileDrop)) { Add-Folder $p }
    })

# ---------- Saved sets (saved under a name) ----------
function Read-Sets {
    # Returns the saved sets one by one
    if (-not (Test-Path -LiteralPath $SetFile)) { return }
    try { $data = ConvertFrom-Json ([IO.File]::ReadAllText($SetFile)) } catch { return }
    foreach ($s in $data) { $s }
}
function Write-Sets($sets) {
    $json = ConvertTo-Json -InputObject @($sets) -Depth 4
    [IO.File]::WriteAllText($SetFile, $json, (New-Object System.Text.UTF8Encoding($false)))
}
function Update-SetList([string]$select) {
    $cmbSet.Items.Clear(); [void]$cmbSet.Items.Add('(choose)')
    foreach ($s in @(Read-Sets)) { [void]$cmbSet.Items.Add($s.name) }
    $cmbSet.SelectedIndex = [Math]::Max(0, $cmbSet.Items.IndexOf($select))
}
$cmbSet.Add_SelectionChangeCommitted({
        $s = @(Read-Sets) | Where-Object { $_.name -eq $cmbSet.SelectedItem } | Select-Object -First 1
        if (-not $s) { return }
        $lstFolders.Items.Clear()
        foreach ($f in $s.folders) { [void]$lstFolders.Items.Add($f) }
        $chkZero.Checked = [bool]$s.skipZero; $chkHidden.Checked = [bool]$s.hidden
        $cmbKeep.SelectedIndex = [int]$s.keep
    })
$btnSetSave.Add_Click({
        if ($lstFolders.Items.Count -eq 0) { Show-Msg 'Add at least one folder before saving.' | Out-Null; return }
        $name = [Microsoft.VisualBasic.Interaction]::InputBox('Name for this set (e.g. My PC plus team share)', 'Save as', '')
        if ([string]::IsNullOrWhiteSpace($name)) { return }
        $sets = @(Read-Sets | Where-Object { $_.name -ne $name })
        $sets += [pscustomobject]@{ name = $name; folders = @($lstFolders.Items); skipZero = $chkZero.Checked; hidden = $chkHidden.Checked; keep = $cmbKeep.SelectedIndex }
        Write-Sets $sets; Update-SetList $name
    })
$btnSetDel.Add_Click({
        if ($cmbSet.SelectedIndex -le 0) { return }
        $name = [string]$cmbSet.SelectedItem
        if ((Show-Msg "Delete the set $name? (No folders or files are deleted.)" 'YesNo' 'Question') -ne 'Yes') { return }
        Write-Sets @(Read-Sets | Where-Object { $_.name -ne $name }); Update-SetList ""
    })
Update-SetList ""

# ---------- Scan (runs on a separate thread so the window does not freeze) ----------
$scanScript = {
    param($sync, $roots, $skipZero, $includeHidden)
    try {
        $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
        $files = New-Object System.Collections.Generic.List[object]
        $skipAttr = [IO.FileAttributes]::Hidden -bor [IO.FileAttributes]::System
        for ($r = 0; $r -lt $roots.Count; $r++) {
            $stack = New-Object System.Collections.Generic.Stack[string]
            $stack.Push($roots[$r])
            while ($stack.Count -gt 0) {
                if ($sync.Cancel) { return }
                $dir = $stack.Pop()
                try {
                    $di = New-Object IO.DirectoryInfo($dir)
                    foreach ($f in $di.GetFiles()) {
                        if (-not $includeHidden -and ($f.Attributes -band $skipAttr)) { continue }
                        if ($skipZero -and $f.Length -eq 0) { continue }
                        if (-not $seen.Add($f.FullName)) { continue }
                        $files.Add([pscustomobject]@{ Root = $r; FullName = $f.FullName; Name = $f.Name; Dir = $f.DirectoryName; Length = $f.Length; LastWrite = $f.LastWriteTime })
                    }
                    foreach ($d in $di.GetDirectories()) {
                        # Do not follow junctions or symbolic links (so no file is counted twice)
                        if ($d.Attributes -band [IO.FileAttributes]::ReparsePoint) { continue }
                        if (-not $includeHidden -and ($d.Attributes -band $skipAttr)) { continue }
                        $stack.Push($d.FullName)
                    }
                } catch { $sync.Errors.Add([pscustomobject]@{ Path = $dir; Message = $_.Exception.Message }) }
                $sync.Status = 'Listing files: {0:N0}' -f $files.Count
            }
        }
        $sync.FileCount = $files.Count

        # Step 1: keep only files that share a size (different size means different content)
        $bySize = New-Object 'System.Collections.Generic.Dictionary[long,System.Collections.Generic.List[object]]'
        foreach ($f in $files) {
            if (-not $bySize.ContainsKey($f.Length)) { $bySize[$f.Length] = New-Object System.Collections.Generic.List[object] }
            $bySize[$f.Length].Add($f)
        }
        $cands = New-Object System.Collections.Generic.List[object]
        foreach ($list in $bySize.Values) { if ($list.Count -gt 1) { $cands.AddRange($list) } }
        $total = 0L; foreach ($c in $cands) { $total += $c.Length }
        $sync.CandCount = $cands.Count; $sync.TotalBytes = $total

        # Step 2: hash (SHA256) only those candidates
        $sha = [Security.Cryptography.SHA256]::Create()
        $buf = New-Object byte[] (1MB)
        $done = 0L; $i = 0
        foreach ($c in $cands) {
            $i++
            $sync.Status = 'Hashing {0:N0}/{1:N0}: {2}' -f $i, $cands.Count, $c.Name
            try {
                $fs = New-Object IO.FileStream($c.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite)
                try {
                    [void]$sha.Initialize()
                    while (($n = $fs.Read($buf, 0, $buf.Length)) -gt 0) {
                        if ($sync.Cancel) { return }
                        [void]$sha.TransformBlock($buf, 0, $n, $null, 0)
                        $done += $n; $sync.DoneBytes = $done
                    }
                    [void]$sha.TransformFinalBlock($buf, 0, 0)
                    $c | Add-Member -NotePropertyName Hash -NotePropertyValue ([BitConverter]::ToString($sha.Hash) -replace '-', '')
                } finally { $fs.Dispose() }
            } catch {
                $sync.Errors.Add([pscustomobject]@{ Path = $c.FullName; Message = $_.Exception.Message })
                $done += $c.Length; $sync.DoneBytes = $done
            }
        }
        # Same size plus same hash = same content
        $byHash = New-Object 'System.Collections.Generic.Dictionary[string,System.Collections.Generic.List[object]]'
        foreach ($c in $cands) {
            if (-not $c.Hash) { continue }
            $key = '{0}|{1}' -f $c.Length, $c.Hash
            if (-not $byHash.ContainsKey($key)) { $byHash[$key] = New-Object System.Collections.Generic.List[object] }
            $byHash[$key].Add($c)
        }
        $sync.Groups = @(foreach ($list in $byHash.Values) { if ($list.Count -gt 1) { [pscustomobject]@{ Count = $list.Count; Group = @($list) } } })
    } catch {
        $sync.Fatal = $_.Exception.Message
    } finally { $sync.Finished = $true }
}

$script:roots = @(); $script:job = $null; $script:sync = $null
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 200

function Set-Busy([bool]$busy) {
    foreach ($c in $btnScan, $btnAdd, $btnRemove, $btnUp, $btnDown, $cmbSet, $btnSetSave, $btnSetDel, $btnUndo) { $c.Enabled = -not $busy }
    $btnCancel.Enabled = $busy
    if ($busy) { foreach ($c in $btnCsv, $btnMove, $btnErrors) { $c.Enabled = $false } }
}

$btnScan.Add_Click({
        if ($lstFolders.Items.Count -eq 0) { Show-Msg 'Add a folder to scan first.' | Out-Null; return }
        $table.Clear(); $lblSum.Text = ''
        $script:roots = @($lstFolders.Items | ForEach-Object { [string]$_ })
        $script:sync = [hashtable]::Synchronized(@{ Cancel = $false; Finished = $false; Status = 'Starting'; DoneBytes = 0L; TotalBytes = 0L; Errors = [Collections.ArrayList]::Synchronized((New-Object Collections.ArrayList)) })
        $script:started = Get-Date
        $rs = [runspacefactory]::CreateRunspace(); $rs.Open()
        $script:job = [powershell]::Create(); $script:job.Runspace = $rs
        [void]$script:job.AddScript($scanScript).AddArgument($script:sync).AddArgument($script:roots).AddArgument($chkZero.Checked).AddArgument($chkHidden.Checked)
        $script:handle = $script:job.BeginInvoke()
        $progress.Value = 0; Set-Busy $true; $timer.Start()
    })
$btnCancel.Add_Click({ if ($script:sync) { $script:sync.Cancel = $true; $lblStatus.Text = 'Stopping...' } })

$timer.Add_Tick({
        $s = $script:sync
        if ($s.TotalBytes -gt 0) { $progress.Value = [int][Math]::Min(100, 100 * $s.DoneBytes / $s.TotalBytes) }
        $lblStatus.Text = $s.Status
        if (-not $s.Finished) { return }
        $timer.Stop()
        [void]$script:job.EndInvoke($script:handle); $script:job.Runspace.Dispose(); $script:job.Dispose()
        Set-Busy $false
        $sec = ((Get-Date) - $script:started).TotalSeconds
        if ($s.Fatal) { Show-Msg ('The scan stopped with an error: ' + $s.Fatal) 'OK' 'Error' | Out-Null }
        if ($s.Cancel) { $lblStatus.Text = 'Stopped'; $progress.Value = 0; return }
        Show-Result $s.Groups
        $progress.Value = 100
        $lblStatus.Text = 'Scanned {0:N0} files (hashed only {1:N0} files, {2}) in {3:N1} s' -f $s.FileCount, $s.CandCount, (Format-Size $s.TotalBytes), $sec
        $btnErrors.Enabled = $s.Errors.Count -gt 0
        $btnErrors.Text = 'Unreadable files ({0})' -f $s.Errors.Count
    })

# ---------- Results, plus which file to keep ----------
function Get-KeepOrder($items) {
    switch ($cmbKeep.SelectedIndex) {
        0 { return $items | Sort-Object Root, @{ e = { $_.FullName.Length } }, FullName }
        1 { return $items | Sort-Object @{ e = { $_.FullName.Length } }, FullName }
        2 { return $items | Sort-Object LastWrite, @{ e = { $_.FullName.Length } } }
        3 { return $items | Sort-Object @{ e = { $_.LastWrite }; Descending = $true }, @{ e = { $_.FullName.Length } } }
    }
}
function Show-Result($groups) {
    $table.Clear()
    $table.BeginLoadData()
    $n = 0
    foreach ($g in ($groups | Sort-Object { [long]$_.Group[0].Length * ($_.Count - 1) } -Descending)) {
        $n++; $first = $true
        foreach ($it in (Get-KeepOrder $g.Group)) {
            # Show the location as <scanned folder name>\<subfolder> to keep it short (the CSV and double-click give the full path)
            $root = $script:roots[$it.Root].TrimEnd('\')
            $place = ((Split-Path $root -Leaf) -replace '[:\\]', '') + $it.Dir.Remove(0, [Math]::Min($root.Length, $it.Dir.Length))
            [void]$table.Rows.Add((-not $first), $n, $it.Name, $place, (Format-Size $it.Length), $it.LastWrite, ($it.Root + 1), $it.FullName, $it.Length, $it.Hash)
            $first = $false
        }
    }
    $table.EndLoadData()
    Set-GridLook; Update-Summary
    $grid.ClearSelection()
}
function Update-Summary {
    $groups = @($table.Rows | Group-Object { $_['Group'] })
    $moveRows = @($table.Rows | Where-Object { $_['Move'] })
    $bytes = 0L; foreach ($r in $moveRows) { $bytes += [long]$r['Bytes'] }
    if ($groups.Count -eq 0) {
        $lblSum.Text = 'No files with identical content were found.'
    } else {
        $lblSum.Text = 'Found {0:N0} groups of identical files ({1:N0} files). Moving the {2:N0} checked files frees {3}. Bold = kept. Double-click a row to open its location.' -f $groups.Count, $table.Rows.Count, $moveRows.Count, (Format-Size $bytes)
    }
    $btnCsv.Enabled = $table.Rows.Count -gt 0
    $btnMove.Enabled = $moveRows.Count -gt 0
}
$cmbKeep.Add_SelectionChangeCommitted({
        # When the rule changes, pick the file to keep again in each group
        foreach ($g in @($table.Rows | Group-Object { $_['Group'] })) {
            $items = foreach ($r in $g.Group) { [pscustomobject]@{ Row = $r; Root = [int]$r['Root'] - 1; FullName = $r['FullName']; LastWrite = $r['Modified'] } }
            $first = $true
            foreach ($it in (Get-KeepOrder $items)) { $it.Row['Move'] = -not $first; $first = $false }
        }
        $grid.Refresh(); Update-Summary
    })
$grid.Add_CurrentCellDirtyStateChanged({ if ($grid.IsCurrentCellDirty) { $grid.CommitEdit('CurrentCellChange') | Out-Null } })
$grid.Add_CellValueChanged({
        param($s, $e)
        if ($e.RowIndex -lt 0 -or $grid.Columns[$e.ColumnIndex].Name -ne 'Move') { return }
        $row = $table.DefaultView[$e.RowIndex].Row
        $g = $row['Group']
        $same = @($table.Rows | Where-Object { $_['Group'] -eq $g })
        if (@($same | Where-Object { -not $_['Move'] }).Count -eq 0) {
            # Moving every file in a group would leave no copy at all, so block it
            $row['Move'] = $false
            Show-Msg 'You cannot move every file in a group. Keep at least one.' 'OK' 'Warning' | Out-Null
        }
        $grid.InvalidateRow($e.RowIndex); Update-Summary
    })
$grid.Add_CellDoubleClick({
        param($s, $e)
        if ($e.RowIndex -lt 0) { return }
        $p = $grid.Rows[$e.RowIndex].Cells['FullName'].Value
        if (Test-Path -LiteralPath $p) { Start-Process explorer.exe -ArgumentList ('/select,"{0}"' -f $p) }
    })

$btnErrors.Add_Click({
        $f = New-Object System.Windows.Forms.Form
        $f.Text = 'Unreadable files or folders (in use, no permission, etc.)'; $f.Size = New-Object System.Drawing.Size(900, 400); $f.StartPosition = 'CenterParent'
        $t = New-Object System.Windows.Forms.TextBox
        $t.Multiline = $true; $t.ScrollBars = 'Both'; $t.WordWrap = $false; $t.ReadOnly = $true; $t.Dock = 'Fill'
        $t.Text = (($script:sync.Errors | ForEach-Object { '{0}  … {1}' -f $_.Path, $_.Message }) -join "`r`n")
        $f.Controls.Add($t); [void]$f.ShowDialog($form)
    })

# ---------- Save as CSV (UTF-8 with BOM so Excel reads it correctly) ----------
$btnCsv.Add_Click({
        $dlg = New-Object System.Windows.Forms.SaveFileDialog
        $dlg.Filter = 'CSV (*.csv)|*.csv'; $dlg.FileName = 'duplicates_{0:yyyyMMdd_HHmmss}.csv' -f (Get-Date)
        if ($dlg.ShowDialog() -ne 'OK') { return }
        $rows = foreach ($r in $table.Rows) {
            [pscustomobject]@{
                'Group' = $r['Group']; 'Status' = $(if ($r['Move']) { 'Move' } else { 'Keep' }); 'Name' = $r['Name']; 'Location' = (Split-Path ([string]$r['FullName']) -Parent)
                'SizeBytes' = $r['Bytes']; 'Modified' = ('{0:yyyy-MM-dd HH:mm:ss}' -f $r['Modified']); 'Folder' = $r['Root']; 'SHA256' = $r['Hash']
            }
        }
        $opt = @{}; if ($PSVersionTable.PSVersion.Major -lt 6) { $opt.NoTypeInformation = $true }
        $lines = $rows | ConvertTo-Csv @opt
        [IO.File]::WriteAllLines($dlg.FileName, [string[]]$lines, (New-Object System.Text.UTF8Encoding($true)))
        Invoke-Item -LiteralPath $dlg.FileName
    })

# ---------- Move to a holding folder ----------
$btnMove.Add_Click({
        $moveRows = @($table.Rows | Where-Object { $_['Move'] })
        if ($moveRows.Count -eq 0) { return }
        $dlg = New-Object System.Windows.Forms.FolderBrowserDialog
        $dlg.Description = 'Choose where to put the files. A duplicates_moved_<date> folder is created inside it, keeping the original folder structure.'
        if ($dlg.ShowDialog() -ne 'OK') { return }
        $baseParent = (Get-Item -LiteralPath $dlg.SelectedPath).FullName.TrimEnd('\') + '\'
        foreach ($root in $script:roots) {
            if ($baseParent.StartsWith($root.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase)) {
                Show-Msg "That location is inside a scanned folder:`n$root`nChoose a place outside it (otherwise the next scan finds these files again)." 'OK' 'Warning' | Out-Null; return
            }
        }
        $bytes = 0L; foreach ($r in $moveRows) { $bytes += [long]$r['Bytes'] }
        $msg = 'Move {0:N0} files ({1})? Nothing is deleted. You can put them back later with Undo a move.' -f $moveRows.Count, (Format-Size $bytes)
        if ((Show-Msg $msg 'YesNo' 'Question') -ne 'Yes') { return }

        $base = Join-Path $baseParent ('duplicates_moved_{0:yyyyMMdd_HHmmss}' -f (Get-Date))
        [void](New-Item -ItemType Directory -Path $base -Force)
        $logPath = Join-Path $base 'move-log.csv'
        $w = New-Object IO.StreamWriter($logPath, $false, (New-Object System.Text.UTF8Encoding($true)))
        $w.AutoFlush = $true
        $w.WriteLine('"Original","MovedTo","SizeBytes","SHA256"')
        $ok = 0; $skip = New-Object System.Collections.Generic.List[string]
        $progress.Value = 0; $i = 0
        try {
            foreach ($r in $moveRows) {
                $i++; $progress.Value = [int](100 * $i / $moveRows.Count)
                $src = [string]$r['FullName']; $root = $script:roots[[int]$r['Root'] - 1]
                $lblStatus.Text = 'Moving: ' + $src; [System.Windows.Forms.Application]::DoEvents()
                $fi = Get-Item -LiteralPath $src -ErrorAction SilentlyContinue
                # Skip files that changed after the scan
                if (-not $fi -or $fi.Length -ne [long]$r['Bytes'] -or $fi.LastWriteTime -ne $r['Modified']) { $skip.Add("$src (changed or deleted after the scan)"); continue }
                $rel = $src.Remove(0, $root.TrimEnd('\').Length).TrimStart('\')
                $leaf = (Split-Path $root -Leaf) -replace '[:\\]', ''
                $dest = Join-Path (Join-Path $base ('{0}_{1}' -f $r['Root'], $leaf)) $rel
                try {
                    [void](New-Item -ItemType Directory -Path (Split-Path $dest -Parent) -Force)
                    Move-Item -LiteralPath $src -Destination $dest -ErrorAction Stop
                    $w.WriteLine(('"{0}","{1}","{2}","{3}"' -f $src.Replace('"', '""'), $dest.Replace('"', '""'), $r['Bytes'], $r['Hash']))
                    $r['Move'] = $false; $r['Location'] = '(moved) ' + $r['Location']; $ok++
                } catch { $skip.Add("$src ($($_.Exception.Message))") }
            }
        } finally { $w.Close() }
        # Drop moved files from the list, plus groups left with a single file
        foreach ($r in @($table.Rows | Where-Object { ([string]$_['Location']).StartsWith('(moved)') })) { $table.Rows.Remove($r) }
        foreach ($g in @($table.Rows | Group-Object { $_['Group'] } | Where-Object { $_.Count -lt 2 })) { foreach ($r in $g.Group) { $table.Rows.Remove($r) } }
        $grid.Refresh(); Update-Summary
        $lblStatus.Text = 'Moved {0:N0} files: {1}' -f $ok, $base
        $text = "Moved {0:N0} files.`nMoved to: {1}`nLog: move-log.csv" -f $ok, $base
        if ($skip.Count) { $text += "`n`nNot moved ({0}):`n{1}" -f $skip.Count, (($skip | Select-Object -First 10) -join "`n") }
        Show-Msg $text | Out-Null
        Start-Process explorer.exe -ArgumentList ('"{0}"' -f $base)
    })

# ---------- Undo (read move-log.csv, put files back) ----------
$btnUndo.Add_Click({
        $dlg = New-Object System.Windows.Forms.OpenFileDialog
        $dlg.Filter = 'Move log (move-log.csv)|move-log.csv|CSV (*.csv)|*.csv'
        $dlg.Title = 'Choose move-log.csv inside the duplicates_moved_<date> folder to undo'
        if ($dlg.ShowDialog() -ne 'OK') { return }
        $log = @(Import-Csv -LiteralPath $dlg.FileName -Encoding UTF8)
        if ($log.Count -eq 0 -or -not ($log[0].PSObject.Properties.Name -contains 'Original')) { Show-Msg 'This file does not look like a move log.' 'OK' 'Warning' | Out-Null; return }
        if ((Show-Msg ('Put {0:N0} files back where they were?' -f $log.Count) 'YesNo' 'Question') -ne 'Yes') { return }
        $ok = 0; $skip = New-Object System.Collections.Generic.List[string]
        foreach ($l in $log) {
            if (Test-Path -LiteralPath $l.'Original') { $skip.Add("$($l.'Original') (a file with that name is already there)"); continue }
            if (-not (Test-Path -LiteralPath $l.'MovedTo')) { $skip.Add("$($l.'MovedTo') (not found in the holding folder)"); continue }
            try {
                [void](New-Item -ItemType Directory -Path (Split-Path $l.'Original' -Parent) -Force)
                Move-Item -LiteralPath $l.'MovedTo' -Destination $l.'Original' -ErrorAction Stop; $ok++
            } catch { $skip.Add("$($l.'Original') ($($_.Exception.Message))") }
        }
        $text = 'Put {0:N0} files back.' -f $ok
        if ($skip.Count) { $text += "`n`nNot restored ({0}):`n{1}" -f $skip.Count, (($skip | Select-Object -First 10) -join "`n") }
        Show-Msg $text | Out-Null
    })

$form.Add_Shown({ Set-GridLook })
$form.Add_FormClosing({ if ($script:sync) { $script:sync.Cancel = $true } })
[void]$form.ShowDialog()

Saved sets are stored in duplicate-file-finder-en.json under %APPDATA%. The tool writes that file only when you save a set. It does not quietly remember your last input.

Design choices

Issue What the tool does
Counting a file twice It does not follow junctions, nor symbolic links. If one scanned folder sits inside another, each file is still counted once
0-byte files Every empty file would match every other one, so they are skipped by default
Unreadable files (in use, no permission) It skips them without stopping. The Unreadable files button lists them
Where to put the moved files It refuses a holding folder inside a scanned folder, since the next scan would flag those files again
SHA256 rather than MD5 On PCs where the FIPS-compliant algorithms policy is enabled, hashing with MD5 has been reported to fail. SHA256 keeps it working on locked-down work PCs

Things to watch out for

  • Other people use the files on a team share. Share the CSV first and confirm the copies can go
  • Shortcuts or Excel links that point at a moved copy will stop working. If that happens, Undo a move puts it back
  • If the holding folder is on another drive, moving means copying, so it takes longer and that drive needs free space. On the same drive, moves finish almost instantly
  • To find which folders are taking up space, see how to list folder sizes. To archive old files, see how to zip up old files with a GUI

Summary

Even on a work PC where you cannot install software, one PowerShell script can find duplicate files. Compare content (hash values), not names, and hash only same-size files to keep it fast. The tool picks the file to keep and moves the rest to a holding folder, so you can always undo. A good first step is to save the CSV and see how many duplicates you have.

References

Comments

Copied title and URL