PowerShell: Compare Two Folders by File Hash to Find Changed Files

スポンサーリンク
PowerShell: Compare Two Folders by File Hash to Find Changed Files File Operations
スポンサーリンク

You have a “before” folder and an “after” folder, and you want a list of files that were added, removed or changed. In PowerShell, the reliable way is to compute a hash of every file and compare the hashes. Comparing names or modified dates is a common tip, but it misses content changes (I tested this below).

At work I use hashes to confirm that prepared materials (config files and so on) haven’t changed behind my back. Listing hashes for one folder is covered in Get-FileHash: export hashes for a whole folder to CSV. Here I compare two such lists and print the differences.

Script to compare two folders

Change the first two lines to your folders: $before is the original, $after the changed one. Paste it into PowerShell and run it. No admin rights needed. Feel free to use it.

It has three parts: Get-HashList builds a list of relative path plus hash for every file under a folder, Compare-Object compares the two lists, and the last part turns the result into Added, Removed or Changed.

$before = "C:\work\before"
$after  = "C:\work\after"

function Get-HashList($root) {
    $root = (Resolve-Path $root).Path
    Get-ChildItem -Path $root -Recurse -File | ForEach-Object {
        [PSCustomObject]@{
            RelativePath = $_.FullName.Remove(0, $root.Length).TrimStart('\')
            Hash         = (Get-FileHash -Path $_.FullName -Algorithm SHA256).Hash
        }
    }
}

$a = Get-HashList $before
$b = Get-HashList $after
$diff = Compare-Object -ReferenceObject $a -DifferenceObject $b -Property RelativePath, Hash

$result = $diff | Group-Object RelativePath | ForEach-Object {
    $sides = $_.Group.SideIndicator
    if ($sides -contains '<=' -and $sides -contains '=>') { $state = 'Changed' }
    elseif ($sides -contains '<=') { $state = 'Removed' }
    else { $state = 'Added' }
    [PSCustomObject]@{ Status = $state; File = $_.Name }
}
$result | Sort-Object File | Format-Table -AutoSize

It prints only the files that differ. Here is the output for the test folders described later:

Status  File
------  ----
Added   new.txt
Removed old.txt
Changed settings.ini

If nothing is printed, the two folders have identical contents.

Reading the result

Status Meaning
Changed In both folders, but the contents differ
Removed Only in the original ($before)
Added Only in the new one ($after)

Files in subfolders appear as relative paths such as sub\data.csv. Because the comparison uses relative paths, the two folders can live in different places and files at the same position are still matched.

Save the result to CSV

To keep a record, run this next. Change the output path as you like.

$result | Sort-Object File | Export-Csv "C:\work\diff.csv" -NoTypeInformation -Encoding UTF8
"Status","File"
"Added","new.txt"
"Removed","old.txt"
"Changed","settings.ini"

In Windows PowerShell 5.1, -Encoding UTF8 writes UTF-8 with a BOM, so Excel shows non-English file names correctly. In PowerShell 7, use -Encoding utf8BOM for the same result.

Why names and modified dates aren’t enough (tested)

Search for folder comparison and you’ll find Compare-Object on file names and modified dates. It’s quick, but it can’t tell you whether contents match. I built test folders to check.

Test folders

The two test folders differ on purpose like this:

File What differs
config.txt Same contents, only the modified date differs
settings.ini Only the contents differ (timeout=30 → timeout=60). Same size and modified date
old.txt Only in before (removed)
new.txt Only in after (added)
sub\data.csv Identical

These commands recreate them under %TEMP%, if you want to try it yourself:

$root = "$env:TEMP\hashtest"
New-Item "$root\before\sub", "$root\after\sub" -ItemType Directory -Force | Out-Null
Set-Content "$root\before\config.txt"   "server=app01"
Set-Content "$root\after\config.txt"    "server=app01"
Set-Content "$root\before\settings.ini" "timeout=30"
Set-Content "$root\after\settings.ini"  "timeout=60"
Set-Content "$root\before\old.txt"      "old file"
Set-Content "$root\after\new.txt"       "new file"
Set-Content "$root\before\sub\data.csv" "id,name"
Set-Content "$root\after\sub\data.csv"  "id,name"
Get-ChildItem $root -Recurse -File | ForEach-Object { $_.LastWriteTime = [datetime]'2026-11-01 10:00' }
(Get-Item "$root\after\config.txt").LastWriteTime = [datetime]'2026-11-02 10:00'
$before = "$root\before"
$after  = "$root\after"

settings.ini is 12 bytes with the same modified date in both folders, so a directory listing can’t tell them apart.

Comparing by name: misses content changes

Compare-Object (Get-ChildItem $before -Recurse -File) (Get-ChildItem $after -Recurse -File) -Property Name
Name    SideIndicator
----    -------------
new.txt =>
old.txt <=

Added and removed files show up, but settings.ini, whose contents changed, doesn’t, because its name is the same.

Comparing name, size and modified date: false alarms and misses

Compare-Object (Get-ChildItem $before -Recurse -File) (Get-ChildItem $after -Recurse -File) -Property Name, Length, LastWriteTime
Name       Length LastWriteTime         SideIndicator
----       ------ -------------         -------------
config.txt     14 11/2/2026 10:00:00 AM =>
new.txt        10 11/1/2026 10:00:00 AM =>
config.txt     14 11/1/2026 10:00:00 AM <=
old.txt        10 11/1/2026 10:00:00 AM <=

config.txt, whose contents are identical, is reported as different, and settings.ini, which really changed, still doesn’t appear. The modified date changes when you just open and re-save a file, and depending on how it was copied. And if an edit keeps the size the same, size won’t catch it either.

Comparing hashes: correct

In the script above, the comparison result ($diff) looked like this:

RelativePath Hash                                                             SideIndicator
------------ ----                                                             -------------
new.txt      CDBA66F93B029372B55EF8112536AED0829A14D70B294C1A9E33A49ED4AD757A =>
settings.ini 8644FF8EFA542A1470E8CBFBF39AE90F6025E542F65D8A61FC1396630E635F26 =>
old.txt      9849BF57C781A24E5CDF242DFDE29370C69C0A5E3C83AB03A1E43FF4ABC55B4D <=
settings.ini B75039373646B8C569AFFEFE71AA79F6E824CFC4D581F2BABA62C4FC037A624B <=

<= means only in before, => only in after. settings.ini has different hashes, so it appears once on each side. config.txt (only the date differs) and sub\data.csv (identical) don’t appear. The script groups these rows per file and labels them Changed, Removed or Added.

When you’re done, delete the test folders:

Remove-Item "$env:TEMP\hashtest" -Recurse -Force

Things to keep in mind

  • Many or large files take time, because hashing reads every file to the end. If you only need added and removed files first, compare names to narrow it down, then hash just the folders that matter
  • Keep the “before” list and you can compare later. Save the Get-HashList output to CSV before handing out materials, and later you can check whether anyone changed them
  • It also works for checking that a NAS backup copied correctly (my backup setup: Back up a local folder to a password-protected NAS with Robocopy)
  • I tested it on local folders
  • If saving it as a .ps1 file gives “running scripts is disabled on this system”, you need to change the execution policy (about_Execution_Policies - Microsoft Learn)

Summary

  • To compare two folders reliably, build lists of relative paths and hashes and compare them with Compare-Object
  • A file on both sides is Changed, only in before is Removed, only in after is Added
  • Comparing names misses content changes; comparing dates or sizes gives false alarms and misses

References

コメント

Copied title and URL