0

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.

  • 2
    Seems like you're missing `$object1.Split(',') $object2.Split(',')` – Santiago Squarzon Jul 07 '23 at 16:37
  • 1
    You’ve not got two “*objects*” - you’ve got two *strings* (ok, strictly speaking a string is also an object by inheritance, but it’s just being treated as a linear sequence of characters by ```Compare-Object```). If you want to give meaning to *parts* of the string then you’ll need to convert it into something else - for example splitting it into an array of substrings like @SantiagoSquarzon suggests with ```.Split(‘,’)``` so that ```Compare-Object``` can compare the *parts* and not the whole string as a single value… – mclayton Jul 07 '23 at 17:11

1 Answers1

0

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.

Shiden67
  • 33
  • 8