Search code examples
powershellhashtable

How to create a hashtable using using values from 2 other hashtables in Powershell


Lets say I have 2 hashtables :

$table1 = @{"A" = "1";
        "B" = "2";
        "C" = "3"}

$table2 = @{"D" = "3";
        "E" = "5";
        "F" = "7"} 

I want to create a third one using Table1 values as keys

$newTable = @{"1" = "3";
          "2" = "5";
          "3" = "7"}`

Kind of new to Powershell. Thx much


Solution

  • A hashtable's order is not preserved by default. For your usecase, you need to make sure the order is being preserved using the [ordered] type:

    $table1 = [ordered]@{
        "A" = "1";
        "B" = "2";
        "C" = "3"
    }
    $table2 = [ordered]@{
        "D" = "3";
        "E" = "5";
        "F" = "7"
    } 
    

    There is no single method that really does the functionality you want, but what we can do is iterate through the values of both of the hashtables and map them together in a new hashtable

    $newTable = [ordered]@{}
    0..($table1.count - 1) | 
        % { 
            $newTable.add(([Array]$table1.values)[$_], ([Array]$table2.values)[$_]) 
        }