Monthly Archive

Property Order

A comment was left on my recent post regarding the creation of objects that implied using a hash table (in the –property parameter of New-Object) could cause problems because there is no control over the order of the properties.

My question is why do you need to control the order of the properties. The whole point of PowerShell is that we are working with .NET based objects whose properties have names. We work with the names not property number 1 or property number 3.

This function creates a new object based on the returns of get-process

001
002
003
004
005
006
007
008
009
010
011
012
function test-process {
get-process | foreach {
 $process = New-Object PSObject -Property @{
   Name = $_.ProcessName
   Id = $_.Id 
   Handles = $_.Handles
   StartTime = $_.StartTime
   Responding = $_.Responding
 }
 $process
}
}

 

Run the script to create the function then try these commands

test-process                                                                                                                                                      

test-process | ft -a                                                                                                                                              
test-process | sort name | ft –a                                                                                                                                  

test-process | Export-Csv tp.csv                                                                                                                                  

Import-Csv tp.csv                                                                                                                                                 
Import-Csv tp.csv | ft –a  

Import-Csv tp.csv | select Name, Starttime | sort starttime -desc | ft

 

Everything works -  we have objects with properties and we work with the properties by name

We shouldn’t need to care about the order of the properties on an object.  I can see a vague argument that if we are trying to use the valuefrompipeline attribute on an advanced function we may have problems but we can easily overcome that by adding ValueFromPipelineByPropertyName.

I have never seen a problem caused by the order of properties.  If you have seen an issue please leave an example.

3 Responses to Property Order

Leave a Reply