Exploring Compare-Object in PowerShell
Welcome back to Wahman’s PowerShell Blog! Today we will explore a very useful cmdlet in PowerShell: Compare-Object. Whether you’re comparing text files, folder contents, or collections of objects, Compare-Object
can be your best friend.
According to Microsoft:
Compare-Object
Compares two sets of objects.
What does Compare-Object do?
Compare-Object
takes two collections (think arrays, lists, or output from other cmdlets) and identifies differences between them. The result will indicate which side (Set 1 or Set 2) the difference originated from using =>
or <=
symbols.
Example 1: Comparing Two Simple Arrays (Beginner)
$array1 = @("apple", "banana", "cherry")
$array2 = @("banana", "cherry", "date")
Compare-Object -ReferenceObject $array1 -DifferenceObject $array2
Output:
InputObject SideIndicator
----------- -------------
apple =<
date =>
This tells us that apple
exists only in the first array, and date
only in the second.
Example 2: Check for File Differences (Intermediate)
$file1 = Get-Content -Path "C:\temp\original.txt"
$file2 = Get-Content -Path "C:\temp\modified.txt"
Compare-Object -ReferenceObject $file1 -DifferenceObject $file2
This is helpful for line-by-line comparisons of text files.
Example 3: Compare Hashtable Keys (Advanced)
$hash1 = @{ Name = "Alice"; Age = 30; City = "Stockholm" }
$hash2 = @{ Name = "Alice"; Age = 30; Country = "Sweden" }
$keys1 = $hash1.Keys
$keys2 = $hash2.Keys
Compare-Object -ReferenceObject $keys1 -DifferenceObject $keys2
This will show that City
is present in the first hashtable, while Country
is present in the second one.
Example 4: Compare Folder Contents Recursively (Advanced)
$folder1 = Get-ChildItem -Path "C:\FolderA" -Recurse | Select-Object -ExpandProperty FullName
$folder2 = Get-ChildItem -Path "C:\FolderB" -Recurse | Select-Object -ExpandProperty FullName
Compare-Object -ReferenceObject $folder1 -DifferenceObject $folder2
This is useful when validating folder syncs or backup consistency.
Summary
Compare-Object
is a powerful tool in your PowerShell toolbox. From string arrays to folder trees, this cmdlet offers flexibility for a wide variety of comparison tasks. It’s straightforward for beginners and still highly useful in advanced scripts.
Happy scripting, and I will see you in the next post!
Leave a Reply