2

I've got a list of object with some fields. For example, there are three object of my list:

Field1 = "aaa"
Field2 = 123
Field3 = "ccc"

Field1 = "bbb"
Field2 = 123
Field3 = "ddd"

Field1 = "eee"
Field2 = 123
Field3 = "ccc"

I need to filter this list like this:

  • I must take all unique occurrences of pair Field2-Field3. Value of Field1 is unnecessary.

In my example, the result of selecting must delete the third object because has same value on Field2 and Field3.

I've tried with Select-Object -Unique Field2, Field3 but doesn't filter anything.

I've also tried with Where-Object with same negative result.

Any idea? I'm using older version of powershell so i can't use some of cmdlets.

Thank you.

here's the code: it works, but i need to get also Field1 in my output

$result = @{}
 foreach($item in $myList) {
       $combined = '{0}-{1}' -f $item.Field2, $item.Field3
       if($result.ContainsKey($combined) -eq $false) {
          $result[$combined] = $item
       }
    }
    $result.Values
maures
  • 131
  • 1
  • 2
  • 13
  • *I've tried with `Select-Object -Unique Field2, Field3` but doesn't filter anything.* Can you show [mcve] demonstrating this? [tio.run](https://tio.run/##K8gvTy0qzkjNyfn/30GDSwEIogOCnUuLS/Jz/ZOyUpNLYhUcqsHiIOCWmZqTYqhgq6CUmJiohCpsBBQ2NDJGFTQGqU1OToaorSXBgqSkJKItSElJId2C1NRUcnygqVCjEJyaAzRXF2K8gm5oXmZhaSrUDB2otv//AQ) – user4003407 Apr 06 '18 at 14:31
  • I don't see `$result = @{}` in that code that you posted. – EBGreen Apr 06 '18 at 14:47
  • you're right. now it works, but my output is: Name: Field2-Field3 Value: all-my-object-field-and-values how can select only field that i need? – maures Apr 06 '18 at 15:02

1 Answers1

1

You can use an expression:

$objects | Select -Unique @{n='Combined'; e={'{0}-{1}' -f $_.Field2, $_.Field3}}

Here is another way using a hash:

$result = @{}
foreach($item in $objects){
    $combined = '{0}-{1}' -f $item.Field2, $item.Field3
    if($result.ContainsKey($combined) -eq $false){
        $result[$combined] = $item
    }
}
$result.Values | Select Field1
EBGreen
  • 36,735
  • 12
  • 65
  • 85
  • i can't understand your expression and seems doesn't works on my code. I need also to select Field1 from my object list – maures Apr 06 '18 at 14:05
  • ContainsKey method doesn't exist. i received an error on this line. – maures Apr 06 '18 at 14:26
  • Not sure what you have going on then. ContainsKey is most certainly a valid method on a hash. Please update your question with the actual code you are running. – EBGreen Apr 06 '18 at 14:28
  • @maures Edited to only get Field1 values – EBGreen Apr 06 '18 at 15:09