Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving hashtable order [duplicate]

Tags:

powershell

Let's say I've this script :

$data= @{
    A = 1
    C = 2
    B = 3
}

foreach($key in $data.Keys){
    $item = $data[$key]
    Write-Host "$($key) : $($item)"
}

The output is:

C : 2
B : 3
A : 1

As you can see, the output is in different order that the input.

Is there any way to preserve the order in my dictionary?

My actual requirement is to execute a set of command in order provided in a dictionary.

As a side note, I can workaround using:

$data= @(
  @{ Name="A"; Value=1  }
  @{ Name="C"; Value=2  }
  @{ Name="B"; Value=3  }
)

foreach($item in $data){
    Write-Host "$($item.Name) : $($item.Value)"
}

but the syntax is bit more complex

like image 320
Steve B Avatar asked Nov 03 '16 12:11

Steve B


1 Answers

Requires PowerShell 3, but you can use the [ordered] accelerator to keep things in order.

$data= [ordered]@{
    A = 1
    C = 2
    B = 3
}
like image 108
alroc Avatar answered Nov 04 '22 06:11

alroc