PowerShell

PowerShell: Comparing two Objects with Compare-Object

In this short blog post, I will show you how to compare two PowerShell objects to find differences between them. I will also give you an example on how to create objects for testing purposes. Let’s dive in.

Creating Objects

First, I create two objects with the same attribute names but different values.

# Tabelle 1
$tabelle1 = @()
$werte = '1803','1903','1609'
foreach ($w in $werte) {
$tabelle1 += New-Object -TypeName PSObject -Property (@{
    'Microsoft' = $w
})
}

# Tabelle 2
$tabelle2 = @()
$werte = '1803','1903'
foreach ($w in $werte) {
$tabelle2 += New-Object -TypeName PSObject -Property (@{
    'Microsoft' = $w
})
}

Now we have two objects with different values, or more precisely, one value is different.

Comparing Objects

Next, we will start comparing these two objects to find differences.

I will use the Compare-Object cmdlet for this kind of task.

Compare-Object `
-ReferenceObject $Tabelle1 `
-DifferenceObject $Tabelle2  `
-PassThru

Fair enough. That’s it for today. Comparison successful.

Categories: PowerShell

Tagged as: ,

1 reply »

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.