Union and Intersection of Hashtables in PowerShell


In Union and Intersection in PowerShell? cool one-liners for set operations of arrays are described.

I want to do this with hashtables and have a solution using the keysets of the dictionaries. To extend then to the values, I use for-loops to iterate over the intersection of the keys and copy the values over to new result-hashtables. This looks not clean.

Further research showed solutions with GetEnumerator which is also not clean IMHO.

How can I replace the bloated for loops or enumerators by concise and nice one-liners?

Source code below:



You can use the same technique as for lists, but use the hash table keys, as you indicate in the OP.

For union and intersection you have an additional problem. Of the keys in common between the two hash tables, which value will you keep? Assume you will always keep the value in the first hash table. Then:

Or you could do this which avoids the clone and creates a new hash table


Union and Intersection of Hashtables in PowerShell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply