0

I have populated a powershell dictionary as given below.

    $test=New-Object System.Collections.Generic.Dictionary"[String,String]"
    $test.Add("1.0.0.0", "A"); 
    $test.Add("2.0.0.0", "A"); 
    $test.Add("1.1.0.0", "B"); 
    $test.Add("1.1.1.0", "C"); 
    $test.Add("1.2.0.0", "B"); 
    $test.Add("2.1.0.0", "B"); 
     $test.Add("1.1.2.0", "C");

When i debugged the code in PowerGui editor i can see the $test value as given below

enter image description here

I want to sort the dictionary on the base of Keys. So the resultant out put should come as below.

    {[1.0.0.0,A],[1.1.0.0,B],[1.1.1.0,C],[1.1.2.0,C],[1.2.0.0,B],[2.0.0.0,A],[2.1.0.0,B]}

So for performing the sort on the base of keys and also for looping through the sorted dictionary i used the below code. But unfortunately neither the sort nor the looping not works for me.

    $test=$test.GetEnumerator() | sort -Property Keys
     while ($test.MoveNext()) 
     {
        Write-Host $test.Key + " --> "
                          + $test.Value
                          }

The resultant dictionary after performing the GetEnumerator is given below.

enter image description here

  SO basically i have two requirement.

  1.)Sort the dictionary on the base of keys
  2.)Loop through the sorted dictionary
mystack
  • 4,910
  • 10
  • 44
  • 75
  • There's [SortedDictionary](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2?view=netframework-4.7.1), that's already sorted on keys. Would that work? – vonPryz Aug 17 '20 at 07:40

1 Answers1

4

Just pipe the sorted dictionary to ForEach-Object:

$test.getEnumerator() | Sort-Object -property key | ForEach-Object { "[{0},{1}]" -f ($_.key, $_.value)}

If you want to ensure the values remain sorted in the variable use the [Ordered] object or the SortedDictionary, see this answer

arco444
  • 22,002
  • 12
  • 63
  • 67
  • Thanks now sorting is working. But how to loop through the resulatant dictionary. Below code is not working foreach($te in $test) { Write-Host "Key"$te[0]; Write-Host "Value"$te[1] ; } – mystack Aug 17 '20 at 10:39
  • I got it by using $te.Key and $te.Value after removing the ForEach-Object – mystack Aug 17 '20 at 11:55