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

No comments:

Post a Comment