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
Requires PowerShell 3, but you can use the [ordered]
accelerator to keep things in order.
$data= [ordered]@{
A = 1
C = 2
B = 3
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With