Preserving property order

This is a very common pattern:

$os = Get-CimInstance -ClassName Win32_OperatingSystem 
$comp = Get-CimInstance -ClassName Win32_ComputerSystem

$props = @{
  OS = $os.Caption
  InstallDate = $os.InstallDate
  LastBoot = $os.LastBootUpTime
  Make = $comp.Manufacturer
  Model = $comp.Model
}

New-Object -TypeName PSObject -Property $props

Get some data – in this case a couple of WMI classes and create an output object.

Unfortunately, the output looks like this

Make        : Microsoft Corporation
Model       : Surface Pro 2
LastBoot    : 30/12/2016 09:41:52
OS          : Microsoft Windows 10 Pro Insider Preview
InstallDate : 08/12/2016 13:20:04

The property order is NOT preserved because you’re working with a hash table. If you absolutely have to preserve the property order use an ordered hash table

$os = Get-CimInstance -ClassName Win32_OperatingSystem 
$comp = Get-CimInstance -ClassName Win32_ComputerSystem

$props = [ordered]@{
  OS = $os.Caption
  InstallDate = $os.InstallDate
  LastBoot = $os.LastBootUpTime
  Make = $comp.Manufacturer
  Model = $comp.Model
}

New-Object -TypeName PSObject -Property $props

All you do is add [ordered] in front of the hashtable definition and your output becomes

OS          : Microsoft Windows 10 Pro Insider Preview
InstallDate : 08/12/2016 13:20:04
LastBoot    : 30/12/2016 09:41:52
Make        : Microsoft Corporation
Model       : Surface Pro 2

exactly what you defined

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

3 Responses to Preserving property order

  1. Why don’t you just use:

    $os = Get-CimInstance -ClassName Win32_OperatingSystem
    $comp = Get-CimInstance -ClassName Win32_ComputerSystem

    $props = [PsCustomObject]@{
      OS = $os.Caption
      InstallDate = $os.InstallDate
      LastBoot = $os.LastBootUpTime
      Make = $comp.Manufacturer
      Model = $comp.Model
    }

  2. Ah. Sorry! I would rarely/never use [ordered]@{} followed by new-object because [PsCustomObject]@{} does it all in one go – If there are reasons why [ordered]/new-object ever has a benefit I’ve never found one. Happy New Year!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s