I can not read the array in the order I need as I manually set it in the powershell script. Not many options that I tried:

1 способ $hash = @{"name"="1";"name3"="2";"name0"="3"} foreach ($h in $hash.GetEnumerator()) { $h.Name } 1 способ результат name name0 name3 

As you can see the array is set in one form, the foreach is traversed as it is easier to see.

 2 способ найден на просторах интернета с использованием [ordered] $hash = [ordered]@{"name"="1";"name3"="2";"name0"="3"} foreach ($h in $hash.GetEnumerator()) { $h.Name } 2 способ результат Unable to find type [ordered]: make sure that the assembly containing this type is loaded. 

Then I began to get a little nervous either, or I do not keep the syntax, or powershell does not love me anymore.

 3 Способ Решил применить цикл for (Думал у меня тут получится обмануть и все пройдет) $hash = @{"name"="1";"name3"="2";"name0"="3"} for ($i=0;$i -lt $hash.count;$i++) { $i $hash[$i] } 3 Способ результат 0 1 2 

As can be seen in the last method, he correctly counted the number of elements, but does not want to withdraw by the index.

And I repeat the problem.

I need the loop to be executed in the order that is necessary for me, namely, since I registered it in $ hash. That is: name name3 name0

  • For associative arrays, order conservation is usually not guaranteed. - Nick Volynkin

1 answer 1

$hash = [ordered]@{"name"="1";"name3"="2";"name0"="3"} works in PowerShell 4.0 at least.

If you cannot upgrade to PowerShell 4.0, then try this option:

 $dict = New-Object 'System.Collections.Generic.Dictionary[[string],[int]]' $dict.add('name', 1); $dict.add('name3', 2); $dict.add('name0', 3); 

enter image description here

  • Yes, that is right. Thank! - Michael