Compare-Object with different property names

Welcome Forums General PowerShell Q&A Compare-Object with different property names

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
11 months, 3 weeks ago.

  • Author
    Posts
  • #90178

    Participant
    Points: 1
    Rank: Member

    Is there a way to compare objects that do not have the same property names? I know how to do this if the property names were the same, but not if they are different

    $people1 = 
    @([pscustomobject]@{name="Robin";age=32;status="S"},
    [pscustomobject]@{name="Tom";age=29;status="M"},
    [pscustomobject]@{name="Ralph";age=12;status="D"})
    $people2 = 
    @([pscustomobject]@{firstname="Robin";age=32;info="S"},
    [pscustomobject]@{firstname="Tom";age=29;info="M"},
    [pscustomobject]@{firstname="Ralph";age=12;info="D"})
  • #90181

    Keymaster
    Points: 1,704
    Helping HandTeam Member
    Rank: Community Hero

    Nope. You'll have to run them through Select-Object and rename the properties to normalize them.

  • #90230

    Participant
    Points: 1
    Rank: Member

    Whaaa??? I was using Select-Object yesterday to rename the Property to no avail. I restarted my computer this morning and Wahla, it works. I don't know......it's voodoo, haha. Thanks.

  • #90233

    Participant
    Points: 91
    Rank: Member
    #region Input
    $people1 = @(
        [pscustomobject]@{name="Robin";age=32;status="S"},
        [pscustomobject]@{name="Tom";age=29;status="M"},
        [pscustomobject]@{name="Ralph";age=12;status="D"}
    )
    
    $people2 = @(
        [pscustomobject]@{firstname="Robin";age=32;info="S"},
        [pscustomobject]@{firstname="Tom";age=29;info="M"},
        [pscustomobject]@{firstname="Ralph";age=12;info="D"}
    )
    #endregion
    
    # Normalize $people1 objects
    $NormalizedPeople1 = $people1 | select @{n='firstname';e={$PSItem.name}},age,@{n='info';e={$PSItem.status}}
    
    # Now both object arrays have the same properties: firstname, ago, info => normalized
    
    # We can now use compare-object to compare $NormalizedPeople1 and $people2
    

The topic ‘Compare-Object with different property names’ is closed to new replies.