fbehrens
fbehrens

Reputation: 6543

How do I read the order of properties from PSCustomObject?

Does PSCustomObject's know the order in which its properties are added?

# Order of properties
$o21 = New-Object PSCustomObject |
  Add-Member NoteProperty a2 2 -passThru |
  Add-Member NoteProperty a1 1 -passThru
$o21 | fl

a2 : 2
a1 : 1

$o12 = New-Object PSCustomObject |
  Add-Member NoteProperty a1 1 -passThru |
  Add-Member NoteProperty a2 2 -passThru
$o12 | fl

a1 : 1
a2 : 2

I want to read this order. How?

Upvotes: 1

Views: 2363

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174515

To get an ordered list of properties of an object in PowerShell, you can access the Properties collections through the hidden psobject memberset property:

PS C:\> $o12.psobject.Properties

MemberType      : NoteProperty
IsSettable      : True
IsGettable      : True
Value           : 1
TypeNameOfValue : System.Int32
Name            : a1
IsInstance      : True

MemberType      : NoteProperty
IsSettable      : True
IsGettable      : True
Value           : 2
TypeNameOfValue : System.Int32
Name            : a2
IsInstance      : True

Expand the Name property if you just want an ordered list of property names using Select-Object:

$PropertyNames = $o12.psobject.Properties |Select-Object -ExpandProperty Name

or using property enumeration (PowerShell 3.0+):

$PropertyNames = $o12.psobject.Properties.Name

Upvotes: 5

scrthq
scrthq

Reputation: 1076

To expand on Mathias' answer; if you are looking to get the property list for an array of objects, you'll need to do one of the following depending on how different the objects in the array are:

  1. All objects in the array share the same properties: This example will pull the first object of the array only and grab its property names

    $PropertyNames = $o12[0].PSObject.Properties | Select-Object -ExpandProperty Name
    
  2. Objects in the array do not share properties:

    $PropertyNames = $o12 | ForEach-Object { $_.PSObject.Properties | Select-Object -ExpandProperty Name}
    

In both of the examples, the takeaway is that property enumeration will happen at the top level. If your top level is an object array and not a PSCustomObject/PSObject, then you'll return array properties and not the properties of the object/objects in the array:

PS> $obj.PSObject.Properties.Name
Count
Length
LongLength
Rank
SyncRoot
IsReadOnly
IsFixedSize
IsSynchronized

PS> $obj[0].PSObject.Properties.Name
Name
SamAccountName

Upvotes: 0

Related Questions