Sunday, December 16, 2018

Creating an object with New-Object -Property won't preserve property order

A convenient way to create PowerShell objects with a given set of properties and values is to make a psobject with New-Object and supply the data in a hashtable literal to the -Property switch. But since hashtables are unordered, this will add the properties to the object in a jumbled order. For example, New-Object psobject -Property @{'a' = 1; 'b' = 2; 'c' = 3; 'd' = 4} produces:

c d b a
- - - -
3 4 2 1

If you're going to display the objects raw and want a nice order to their properties, you need to create a plain psobject and add the properties one at a time in the desired order with Add-Member.

No comments:

Post a Comment