Search code examples
powershellhashtable

Adding a hash-table to a hash-table


I'm trying to add a hash-table to a hash-table using powershell. However, Im getting the following error:

Item has already been added. Key in dictionary: 'Dev' Key being added: 'Dev'

Here's my code:

$colors = @("black","white","yellow","blue")

$Applications=@{}

Foreach ($i in $colors)
{
    $Applications += @{
        Colour = $i
        Prod = 'SrvProd05'
        QA   = 'SrvQA02'
        Dev  = 'SrvDev12'
    }
}

What am I doing wrong?


Solution

  • I think what you want is something more like this:

    $colors = @("black","white","yellow","blue")
    $Applications=@{}
    Foreach ($i in $colors)
    {
        $Applications[$i] = @{
            Colour = $i
            Prod = 'SrvProd05'
            QA   = 'SrvQA02'
            Dev  = 'SrvDev12'
        }
    }
    

    I will also point out that Hashtables often need to be handled defensively. Each key must be unique but values do not need to be. Here is the typical method of handling that:

    $colors = @("black","white","yellow","blue")
    $Applications=@{}
    Foreach ($i in $colors)
    {
        if($Applications.ContainsKey($i)){
            #Do things here if there is already an entry for this key
        }else{
            $Applications[$i] = @{
                Colour = $i
                Prod = 'SrvProd05'
                QA   = 'SrvQA02'
                Dev  = 'SrvDev12'
            }
        }
    }