Recently I had to compare a bunch of directory pairs and while PowerShell offers the Compare-Object, I needed something more that would not only look at filenames but compare binary files as well. Figuring some nice person on the Internet had already implemented this, I thought I’d just borrow and go about my business. Turns out there were lots of people asking about comparing directories, but not combining both filename and binary comparisons. Other than a mercifully brief divergence into PowerShell custom objects because I always wondered what they were, it wasn’t too hard to implement Compare-Directories.
Below is the help for Compare-Directories that shows how it works. As always, you can get the latest WintellectPowerShell module at it’s happy home on GitHub: https://github.com/Wintellect/WintellectPowerShell. If you follow the project on GitHub you’ll get these updates automatically.
Compare-Directories
SYNOPSIS
Compare two directories to see if they are identical
SYNTAX
Compare-Directories [-OriginalDir] <String> [-NewDir] <String> [[-Excludes] <String[]>] [-Recurse] [-Force]
[-Content] [<CommonParameters>]
DESCRIPTION
This cmdlet will compare two directories and report if the files are identical by name, and optionally on content.
Symbol explanation:
=> – The file is in the -NewDir directory, not the -OriginalDir.
<= – The file is in the -OriginalDir directory and not the -NewDir.
!= – The file is in both directories, but the content is not identical.
If the directories are identical an empty hash table is returned.
Since sometimes filenames are long, you can pipe this output of this cmdlet into Format-Table -AutoSize to avoid
truncating the filenames.
PARAMETERS
-OriginalDir <String>
The original directory to use for the comparison.
-NewDir <String>
The new directory to compare to.
-Excludes <String[]>
The array of exclusions, including wildcards, so you can filter out some of the extraneous files.
-Recurse
Recurse the directory tree. The default is to just look at the directory.
-Force
Allows the cmdlet to get items that cannot otherwise not be accessed by the user, such as hidden or system
files.
-Content
Check the content of matching filenames in both directories to see if they are equal. This is done through the
Get-Hash cmdlet also in this module.
OUTPUTS
HashTable
The name is the file, and the value is the difference indicator. If the directories are identical, an empty
hash table is returned.
————– Example 1 ————–
C:\PS>Compare-Directories .\Original .\Copied -Content
Compares the original directory against a copied directory for both filenames and content.
This shows that both file a.pptx, and c.pptx are in both directories but the content is different. Files f.pptx
and i.pptx are only in the .\Copied directory.
Name Value
—- —–
a.pptx !=
c.pptx !=
f.pptx =>
i.pptx =>