Snippet: Diff Objects

We will use Compare-Object1 for this task. Even though it is not expressly built for diffing content it works fine for that.

Diff Data Inside Arrays#

$array1 = @(
    "Hello World",
$array2 = @(
    "Hello World",
Compare-Object -ReferenceObject $array1 -DifferenceObject $array2

Diff Files#

# To diff two files just load there contents and diff the resulting objects
$objects = @{
  ReferenceObject = (Get-Content -Path file1.txt)
  DifferenceObject = (Get-Content -Path file2.txt)
Compare-Object @objects -IncludeEqual -ExcludeDifferent


  • To get all matches instead of differences use this

    Compare-Object @objects -IncludeEqual -ExcludeDifferent
  • -PassThrough allows us to get the diff in the original data type instead of PSCustomObject and we can still access the .SideIndicator property

  • IComparable2

    If the object implements IComparable, the cmdlet searches for ways to compare the objects. If the objects are different types, the Difference object is converted to the type of the ReferenceObject then compared.

  • We can compare by properties of the source objects and even script blocks for custom comparisons

  1. Docs: Compare-Object ↩︎

  2. Docs: IComparable Example ↩︎