1

Here is a short script that gives an example of the behavior in question:

$foo = New-Object -TypeName PSCustomObject -Property @{
    Username = "BSmith"
    OU = "Finance"
    Department = "Finance"
    Description = "Accounts"
    Office = "345 2nd St"
    ServerName = "WFINANCE"
    ShareName = "BSmith$"
    LocalPath = "E:\Users\BSmith"
    }

Write-Host $foo

The output is: @{ServerName=WFINANCE; Office=345 2nd St; Username=BSmith; LocalPath=E:\Users\BSmith; OU=Finance; Description=Accounts; ShareName=BSmith$; Department=Finance}

As you can see, the order of the variables being output is different than the order given when they were specified. Why is this, and how can I make the order consistent?

I have only had the chance to test this on one computer, but the order of the output is consistent between executions of the script. It also doesn't make a difference how I order the properties when declaring them. I haven't been able to test and see if a different machine will return a different order.

Dennis
  • 871
  • 9
  • 29
Bobazonski
  • 1,515
  • 5
  • 26
  • 43
  • possible duplicate of [Change order of columns in the object](http://stackoverflow.com/questions/19624597/change-order-of-columns-in-the-object) – briantist Jul 29 '15 at 21:30
  • In particular I think [this answer](http://stackoverflow.com/a/19625107/3905079) is what you're looking for. Use the type accelerator instead of `New-Object`. – briantist Jul 29 '15 at 21:31

1 Answers1

4

Define the list of properties beforehand as an [ordered] hashtable, then create the object from that hashtable:

$properties = [ordered]@{
  Username    = "BSmith"
  OU          = "Finance"
  Department  = "Finance"
  Description = "Accounts"
  Office      = "345 2nd St"
  ServerName  = "WFINANCE"
  ShareName   = "BSmith$"
  LocalPath   = "E:\Users\BSmith"
}
$foo = New-Object -TypeName PSCustomObject -Property $properties

Note that this requires PowerShell v3 or newer.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328