compare-object left or right side only
Asked Answered
F

2

9

Quick Question

Is there a better (i.e. more efficient / more concise) way to do this?

compare-object $a $b | ?{$_.SideIndicator -eq '<='}

Detail

Compare-Object gives paramenters -excludeDifferent and -includeEqual to allow you to amend which results you get.

  • using both gives you an inner join
  • using just -includeEqual gives you a full outer join
  • using just -excludeDifferent is pointless; as by default equal items are excluded, so it will now exclude everything.

There are no options for -includeLeft, -excludeLeft or similar.

Currently to do a left outer join where the right side is null (i.e. items in the reference object which are not in the difference object) I need to filter the results manually, as per the code above.

Have I missed something / is there a better way?

http://ss64.com/ps/compare-object.html

Fertilization answered 5/2, 2015 at 10:53 Comment(1)
Submitted feature request: connect.microsoft.com/PowerShell/feedbackdetail/view/1116603/…Fertilization
S
4

there is no option like that for that cmdlet, however you could create a filter (in your profile for example) and then use it to filter the result : something like

filter leftside{
param(
        [Parameter(Position=0, Mandatory=$true,ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [PSCustomObject]
        $obj
    )

    $obj|?{$_.sideindicator -eq '<='}

}

usage

compare-object $a $b | leftside
Sacramentarian answered 5/2, 2015 at 11:13 Comment(2)
I'd not yet discovered filters, so extra thanks for that pro tip!Fertilization
filter was early introduced in PS but I think it could be completely replace with a functionIreful
C
1

You can also add -property SideIndicator and use an if statement for it.

$Missing = compare-object $Old $new -Property Name,SideIndicator
     ForEach($Grp in $Missing) {
          if($grp.sideindicator -eq "<=") {     
          # Do Something here
          }
     }
Commercialize answered 12/12, 2018 at 20:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.