PowerShell Compare-Object (Inlcuding Equals)

68 Views Asked by At

I am trying to compare two objects in PS.

$object1 = "1.1.1.1,2.2.2.2,3.3.3.3" $object2 = "3.3.3.3,4.4.4.4"

How do I compare these two objects and include similarities into a new variable?

I've tried - $compare = Compare-Object -IncludeEqual $object1 $object2 | Select -ExpandProperty InputObject

But no luck with the whole Compare-Object cmdlet.

1

There are 1 best solutions below

0
Shiden67 On

I would split the two objects into two String arrays and compare their content.

Here an example:

$Object1 = "1.1.1.1,2.2.2.2,3.3.3.3"
$SplitedObject1 = $Object1.Split(",")

$Object2 = "3.3.3.3,4.4.4.4"
$SplitedObject2 = $Object2.Split(",")

$res = Compare-Object -ReferenceObject $SplitedObject1 -DifferenceObject $SplitedObject2 -IncludeEqual | Where-Object {$_."SideIndicator" -eq "=="} | ForEach-Object {$_."InputObject"}

In the res variable you will find 3.3.3.3.

I hope that could help you in some way.