Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select-object -expandproperty with null property

I have a collection of objects with properties like id, username, email, current_sign_in_at, identities. Where Identities property is an array of objects with two properties. This would be a json representation of an object:

{
        "id": 45,
        "name": "Emilio Roche",
        "username": "EROCHE",
        "state": "active",
        "identities": [
            {
                "provider": "ldapmain",
                "extern_uid": "cn=roche\\, emilio,ou=xxxxxxxxxx"
            }    
          ]
    }

But some of the elements in the list do not have the identities property. So, when I do:

Get-Collection | Select-Object id, username  -ExpandProperty identities

I get only those elements with identities property. I need all the entities, with or without identities property

like image 909
mnieto Avatar asked Dec 23 '22 02:12

mnieto


1 Answers

If there are not too many properties to handle, you could use something like this:

Get-Collection | Select-Object id, 
    username,
    @{n='provider';e={$_.identities.provider}}, 
    @{n='extern_uid';e={$_.identities.extern_uid}}

This will return $null on the properties provider and extern_uid for those objects, that do not have the identities property:

id username provider extern_uid                     
-- -------- -------- ----------                     
45 EROCHE   ldapmain cn=roche\, emilio,ou=xxxxxxxxxx
46 EROCHE                                           

EDIT

As mklement0 pointed out, that approach doesn't work, if the identities property holds more than one object.

mklement0's answer has an elegant solution to this problem and should have been the accepted answer.

like image 97
Manuel Batsching Avatar answered Feb 02 '23 04:02

Manuel Batsching