Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get-Member does not return NoteProperty when using multiple psobjects

Tags:

powershell

This is odd behavior I have discovered due to the structure of some JSON I am trying to process. I am simply trying to return all the property names. This is my JSON:

$x = @"
[
    {
        "test":  [
            "item1"
        ]
    },
    {
        "test2":  [
            "item2"
        ]
    }
]
"@ | ConvertFrom-Json

You may also create the objects like so, which results in the same issue:

$x= @()

$x += [pscustomobject]@{
    'test' = 'item1'
}

$x += [pscustomobject]@{
    'test2' = 'item2'
}

Notice that now, I can write $x | fl and get all this information as per usual.

$x | fl


test : item1

test2 : item2

However, when using Get-Member, only the first object is included.

$x | Get-Member -MemberType NoteProperty

Name MemberType   Definition       
---- ----------   ----------       
test NoteProperty string test=item1

Does anyone know why this is? I cannot change the JSON structure.

like image 354
Jacob Colvin Avatar asked Feb 18 '26 16:02

Jacob Colvin


1 Answers

Get-Member looks at the first item (of each distinct type) in the pipeline to determine the set of properties to use.

Out-GridView and other cmdlets like Export-CSV do the same thing.

It has nothing to do with the fact that these are PSCustomObjects. Here's an example with FileInfo objects:

$files = Get-ChildItem -Path C:\temp -File |
    Select-Object -First 2

#Add a property to second item
$files[1] | Add-Member -MemberType NoteProperty -Name Test -Value 'hello world'

#doesn't show Test, because it wasn't in the first item
$files | Get-Member


$files2 = Get-ChildItem -Path C:\temp -File |
    Select-Object -First 2

#add property to first item
$files2[0] | Add-Member -MemberType NoteProperty -Name Test -Value 'hello world'

#shows Test, because it was in the first item
$files2 | Get-Member
like image 121
Mike Shepard Avatar answered Feb 20 '26 17:02

Mike Shepard