ca9163d9
ca9163d9

Reputation: 29159

Find difference between two array of psobject?

The following code creates two sample array of psobject. How to get the difference of $a and $b by property A and X where A*2 <> X (just an example, it can be any complex predict)?

$a = 1..5 | % { New-Object -TypeName psobject -Property (@{A = $_; B= "..." }) }
$b = 2..6 | % { New-Object -TypeName psobject -Property (@{X = $_*2; Y= "..." }) }

The list of item(s) in $a but not in $b: 1

The list of item(s) in $b but not in $a: 12

Basically, if the code is written in a F#/C# language. It will require something like not (list.Exists(x => predict(x))), which needs a lambda.

Upvotes: 0

Views: 1019

Answers (2)

TheMadTechnician
TheMadTechnician

Reputation: 36297

Skipping the compare-object cmdlet you could iterate through $a and check if a calculated property of each object is in the array of values for whatever property for $b. That sounds confusing, but I think an example should help...

$a|?{($_.a*2) -notin $b.x}

Or reversed:

$B|?{($_.x/2) -notin $A.a}

I suppose you could make a function for it, something like:

Function CalculatedCompare{
Param(
    [Object[]]$InputObject,
    [String]$InputProperty,
    [Object[]]$DifferenceObject,
    [String]$DifferenceProperty,
    [String]$Conversion
)
    $InputObject | Where{$([ScriptBlock]::Create("$($_.$InputProperty)$conversion").Invoke()) -notin $differenceobject.$differenceproperty}
}

I just kind of made that up on the fly, but I don't see any reason that it wouldn't work off the top of my head.

Ok, I just pasted it into the ISE and it works. Using your sample data I did:

CalculatedCompare $a 'a' $b 'x' '*2'

And the function spit back the one record where $A.A is '1'.

Upvotes: 0

CB.
CB.

Reputation: 60918

This maybe?

The list of item(s) in $a but not in $b:

Compare-Object $a $b -Property a,b | ? { $_.SideIndicator -eq "<=" } |
  select -Expand a

The list of item(s) in $b but not in $a:

Compare-Object $a $b -Property a,b | ? { $_.SideIndicator -eq "=>" } |
  select -Expand a

Upvotes: 1

Related Questions