powershellcustom-object

Construct custom object from two objects


I have two objects:

PropID     ValueX
---------- ------------
      8039 xxxx
      8041 xxxx
      8042 xxxx
PropID     ValueY
---------- -------
      8039 yyyy
      8041 yyyy
      8042 yyyy

I want to end up with a new object containing PropName,ValueX,ValueY (based on the PropID), like this:

PropID     ValueX       ValueY
---------- ------------ ----------
      8039 xxxx         yyyy
      8041 xxxx         yyyy
      8042 xxxx         yyyy

I know it's simple but I'm rusty this moring and could use a helping hand.

*Not the same as In Powershell, what's the best way to join two tables into one? since I Don't want to use any third-party cmdlet but only native PowerShell.


Solution

  • This is just an example using $o1 as the object array that contains ValueX and $o2 as the object array that contains ValueY. Maybe this will get you started in a desirable direction.

    $o1 = @( [pscustomobject]@{
        propID = 1
        ValueX = 334
        }) -as [collections.generic.list[object]]
    $o1.add([pscustomobject]@{
        propID = 3
        ValueX = 34324
        })
    $o1.add([pscustomobject]@{
        propID = 2
        ValueX = 534
        })
    
    $o2 = @( [pscustomobject]@{
        propID = 1
        ValueY = 867
        }) -as [collections.generic.list[object]]
    $o2.add([pscustomobject]@{
        propID = 2
        ValueY = 873
        })
    $o2.add([pscustomobject]@{
        propID = 3
        ValueY = 89722
        })
    
    $newobject = $o1 | Foreach-Object { 
                $_.psobject.copy()
               }
    $newobject |
        Foreach-Object {
            $obj = $_
            $_ | Add-Member -MemberType NoteProperty -Name ValueY -Value $o2.where{$_.propid -eq $obj.propid}.ValueY
        }