Merge-Hashtable

PowerShell is capable of just appending hashtables like: @{a = 1; b = 2} + @{c = 3; d = 4} but in case there is an overlap in the tables and the keys are not unique, you will receive an error:

The resolve this, it is important to decide what to do with values of the duplicate keys, keep the ones in the first table supplied, overrule them with any new table, or do something more advance like; calculating the average?
The Merge-Hashtable cmdlet below will by default put all the values of the duplicated keys in array and let the programmer decides how to merge them if required.

Cmdlet

Syntax

<Dictionary[]> | Merge-Hashtable [[-Operator] <ScriptBlock>]

Merge-Hashtable [-Dictionary <Dictionary[]>] [-Operator <ScriptBlock>]

Parameters

-Dictionary <Dictionary[]>

One or more directories, like hash tables, to be merged.

-Operator <ScriptBlock>

By default, all values from duplicated hash table keys will added to an array. The -Operator  expression is used to merge the array of values resulted from duplicated keys.

Examples

Given the following hashtables:

By default, all values from duplicated hash table keys will added to an array:

To get just the first value of duplicated key use the command:

The just the last value of duplicated key use the command: $h1, $h2, $h3 | Merge-Hashtables{$_[-1]},  or e.g. the largest value: $h1, $h2, $h3 | Merge-Hashtable {($_ | Measure-Object -Maximum).Maximum}.

More examples:

Take the average:

Join the values together:

Sort the values list

 

The Merge-HashTable cmdlet was originally published at StackOverflow

Leave a Reply