How to Compare Directories with PowerShell

Adam Bertram

Read more posts by this author.

Here’s a quick and easy way to compare directories 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 use PowerShell to compare these directories.

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 with the Test-Path cmdlet. The code snippet below will check if the C:\SourceFolder and C:\DestinationFolder exists. If both exist, PowerShell will enter the if statement.

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

If both folders exist, then perform the next check which compares the file names in each folder. You can do this with the Get-ChildItem cmdlet finding all files in each folder and then using Compare-Object to compare each array of file names.

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

Related: Get-ChildItem: Listing Files, Registry Items and More

If both folders contain the same files, you can then perform a more intensive check by comparing the hash of each file.

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

This was a quick and dirty method for using PowerShell to compare directories but it should give you some good ideas and ways to improve it!

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!