Search code examples
powershellhashtablepowershell-2.0powershell-3.0powershell-4.0

How to retrieve a key in a hash table and then update the value in Powershell?


I have a hash table where keys represent email addresses and the values represent a count. The if check sees if the email address is in the hash table, if it is not contained, then add it to the hash table and increment the count.

If the email address is present in the hash table, how do I retrieve the key and then update the value counter?

Thank you!

$targeted_hash = @{}
$count = 0
foreach ($group in $targeted)
{
    if (!$targeted_hash.ContainsKey('group.ManagerEmail'))
    {
        $targeted_hash.Add($group.ManagerEmail, $count + 1)
    }
    else
    {
        #TODO
    }

}    

Solution

  • PowerShell offers two convenient shortcuts:

    • assigning to an entry by key updates a preexisting entry, if present, or creates an entry for that key on demand.

    • using ++, the increment operator on a newly created entry implicitly defaults the value to 0 and therefore initializes the entry to 1

    Therefore:

    $targeted_hash = @{}
    foreach ($group in $targeted)
    {
      $targeted_hash[$group.ManagerEmail]++
    }
    

    After the loop, the hash table will contain entries for all distinct manager email addresses containing the count of their occurrence in input array $group.