Last active
July 8, 2017 23:43
-
-
Save turboBasic/09ce0e4ba30f82eabdd7e3a16e139dc0 to your computer and use it in GitHub Desktop.
Powershell function which merges Hashtables similarly to how lodash _.merge does. Answers question "How do I merge several hashtables while being able both add new keys and overwrite old ones?"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# .SYNOPSIS | |
Merges any number of hashtables into one | |
.DESCRIPTION | |
Merges any number of hashtables taken both from pipeline and arguments, with the hashtables in the right overwriting the keys with the same names from hastables in the left | |
.EXAMPLE | |
$a = @{a = 'a1'; b = 'a2'} | |
$b = @{b = 'b1'; c = 'b2'} | |
$c = @{c = 'c1'; d = 'c2'} | |
PS> Merge-Hashtables $a $b | |
Name Value | |
---- ----- | |
a a1 | |
b b1 | |
c b2 | |
.EXAMPLE | |
PS> $a, $b | Merge-Hashtables $c | |
Name Value | |
---- ----- | |
a a1 | |
b b1 | |
c c1 | |
d c2 | |
#> | |
Function Merge-Hashtables { | |
$Result = @{} | |
($Input + $Args) | | |
Where { ($_.Keys -ne $null) -and ($_.Values -ne $null) -and ($_.GetEnumerator -ne $null) } | | |
ForEach { $_.GetEnumerator() } | | |
ForEach { $Result[$_.Key] = $_.Value } | |
$Result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment