How to Compare the Contents of Two Folders

Adam Bertram

Adam Bertram

Read more posts by this author.

Here’s a quick and easy way to compare the contents of two folders with PowerShell.

Have you ever needed to figure out if two folders had the same files in them? I’m not talking about the same amount of files or even files with the same name but the actual same files? A good way to do this is to generate hashes of all the files in the source directory and the destination directory and compare the two. Let’s find out how to make this happen.

Let’s say I have a folder C:\SourceFolder and C:\DestinationFolder that might have the exact same files in them. I’d like to confirm this.

Creating file hashes is an expensive operation especially if the files are large so I’m going to try other checks first before I have to go to that extent.

First, I can ensure that both folders just exist.

if ((Test-Path -Path C:\SourceFolder) -and (Test-Path -Path C:\DestinationFolder)) {
  ## Both folders exist

Then, I can enumerate the files in each folder to ensure the file names are the same.

$sourceFiles = Get-ChildItem C:\SourceFolder -Recurse
$destFiles = Get-ChildItem C:\DestinationFolder -Recurse
if (Compare-Object $sourceFiles.Name $destFiles.Name) {
  ## Folders have different files

Then, and only then, I’ll go ahead and check the hashes to be sure the files are exactly the same in both folders

if (-not (($sourceFiles.foreach{ Get-FileHash $_.FullName }).Hash -and ($destFiles.foreach{ Get-FileHash $_.FullName }).Hash))
  ## Hashes do not match for all files

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!