Using PowerShell to check a folder copied

I’ve had a number of times over the years where I’ve needed to guarantee to someone that their data is unchanged as a result of an IT action- when we’ve migrated servers, replaced disks etc. The detailed, in depth, article by Jeff Hicks over at “Hashing it Out in PowerShell: Using Get-FileHash” showed me that a file-hash comparison was possible in Windows without a third party piece of software.

So, inspired by that, here’s a short bit of PowerShell script to check two folders are the same- the folder had been previously copied with a ROBOCOPY /MIR command. The script makes two lists of hashes, one for each folder, and compares the two.

$SourceHash = Get-ChildItem -recurse X:\Folder\ | Get-FileHash
$TargetHash = Get-ChildItem -recurse Y:\Folder\ | Get-FileHash
Compare-Object $SourceHash.Hash $TargetHash.Hash

Or if you want to squish it to one line

Compare-Object (Get-ChildItem -recurse X:\Folder\ | Get-FileHash).Hash (Get-ChildItem -recurse Y:\Folder\ | Get-FileHash).Hash

If the two folders are the same (i.e. the Robocopy worked as it should) then no output is displayed. To check it’s working, adding -includeequal to the end of the Compare-Object line will also output a line for identical files. For example

Compare-Object (Get-ChildItem -recurse X:\Folder\ | Get-FileHash).Hash (Get-ChildItem -recurse Y:\Folder\ | Get-FileHash).Hash -includeequal

This should hopefully be a quick and simple solution for others, check out Jeff Hicks’ article or type get-help get-filehash in a PowerShell window for more in-depth information.


Leave a Reply

Your email address will not be published. Required fields are marked *