August 9, 2017

PowerShell - PSObject property order (ordered hash tables)

How to change property order during PSObject output?

$Properties = @{
 a = 1
 b = 2
 c = 3
$Object = New-Object -TypeName PSObject -Property $Properties
$Object 
c b a
- - -
3 2 1

What if you need a,b and then c property order?

$Properties = @{
 a = 1
 b = 2
 c = 3
}
$Object = New-Object -TypeName PSObject -Property $Properties
$Object | select a,b,
a b c
- - -
1 2 3 

Or even simpler, just add [Ordered] before @{
$Properties = [Ordered]@{
 a = 1
 b = 2
 c = 3
}
$Object = New-Object -TypeName PSObject -Property $Properties
$Object 
a b c
- - -
1 2 3

2 comments:

  1. A more concise object creation:
    [PSCustomObject][Ordered]@{
    a = 1
    b = 2
    c = 3
    }

    ReplyDelete