Nick
Nick

Reputation: 1208

I have duplicate keys in a hashtable

I know this is impossible, but I've managed it. From a SQL query, I'm pulling 1, 2, or 3 email addresses which are linked to a device. I'm throwing them into a hashtable. From there, I loop through, check it against a second hashtable which is made up of the values in the first table. This works if there is one email address, but if there is more than one, it's not finding a match, and it is creating a new key.

$DeviceList = @{
    "Device1" = "[email protected]";
    "Device7" = "[email protected]";
    "Device8" = "[email protected]";
    "Device2" = "[email protected]", "[email protected]";
    "Device3" = "[email protected]", "[email protected]";
    "Device4" = "[email protected]", "[email protected]", "[email protected]";
    "Device5" = "[email protected]", "[email protected]", "[email protected]";
    "Device6" = "[email protected]", "[email protected]", "[email protected]"
}
$CompletedDevices = @{}

foreach ($Device in $DeviceList.GetEnumerator()) {
    $Devicename = ($Device.Key).ToLower()
    $OwnerEmail = ($Device.Value).ToLower()

    if ($CompletedDevices.ContainsKey($OwnerEmail)) {
        $CompletedDevices.$OwnerEmail += "$Devicename"
    } else {
        $CompletedDevices += @{$OwnerEmail = " ", $Devicename}
    }
}

$CompletedDevices

After the script runs, if I just run the $CompletedDevices += @{$owneremail = " ", $Devicename}, it DOES give me an error

Item has already been added

but it's not finding it in the ContainsKey() check, and it IS adding it as a second third or fiftieth, duplicate key.

This is what the end result should be for this example:

enter image description here

The example above replicates the issue. I'm really hoping that I'm just overlooking something really simple.

Upvotes: 1

Views: 5373

Answers (1)

Nick
Nick

Reputation: 1208

MathiasR.Jessen put the answer in the comments:

"You don't generate duplicate keys - you're copying the value arrays inside the loop, and the hashtable will accept the resulting objects as keys not by value but by identity.

$CompletedDevices.GetEnumerator()|%{"$($_.Key): $($_.Key.GetHashCode())" }

Change $OwnerEmail = ($Device.Value).ToLower() to $OwnerEmail = "$($Device.Value)".ToLower() "

Both of these solutions helped me greatly, thank you!

Upvotes: 1

Related Questions