Search code examples
powershellhashtable

Powershell - add duplicate key but different values into a hash table


how to add duplicate keys with different values into a hash table so it could be later used in a foreach loop in Powershell? i.e.

$VM = "computer1"

$HashTable = @{ }
$HashTable.Add("key", $VM)

...some script, if statements, ....

$VM = "computer2"
$HashTable.Add("key", $VM)
.....

ForEach ($machine in $HashTable.values)
{
do something for $machine
}

I get an error: "Exception calling "Add" with "2" argument(s): "Item has already been added. Key in dictionary: 'key' Key being added: 'key'"


Solution

  • You can't have duplicate keys in a Hash Table (or dictionary), but you can do this:

    $HashTable = @{}
    
    $VM = "computer1"
    [Array]$HashTable['Key'] += $VM
    
    $VM = "computer2"
    [Array]$HashTable['Key'] += $VM
    
    ForEach ($machine in $HashTable['Key'])
    {
        Write-Host $Machine
    }
    

    But I really question if you want to do this. Instead, I guess your $VM is actually supposed to be the key and than you can do: ForEach ($machine in $HashTable.Keys) {...}