If this really is about merging Hashtables as the title says, then basically you have two options to add the entries from the second hashtable into the first.
1. Use the static method Add()
(first item 'wins')
This has already been explained in vonPryz's answer, but in short:
Adding an entry in a hashtable with a key that already exists in the hash, the Add()
method will throw an exception, because all keys in a hash must be unique.
To overcome that, you need to check if an entry with that key exists and if so, do not add the entry from the second hash.
foreach ($key in $secondHash.Keys) {
if (!$firstHash.Contains($key)) {
# only add the entry if the key (name) did not already exist
$firstHash.Add($key, $secondHash[$key])
}
}
This way, all entries already in the first hashtable will NOT get overwritten and duplicate entries from the second hash are discarded.
2. Overwriting/adding regardless of the existance (last item 'wins')
You can also opt to 'merge' the entries without the need for checking like this:
foreach ($key in $secondHash.Keys) {
# always add the entry even if the key (name) already exist
$firstHash[$key] = $secondHash[$key]
}
This way, if an entry already existed in the first hash, its value will be overwritten with the value from the second hash.
If the entry did not already exist, it is simply added to the first hashtable.
But, what if you want to merge without skipping or overwriting existing values?
In that case, you need to come up with some method of creating a unique key for the entry to add.
Something like this:
foreach ($key in $secondHash.Keys) {
if ($firstHash.Contains($key)) {
# ouch, the key already exists..
# now, we only want to add this if the value differs (no point otherwise)
if ($firstHash[$key] -ne $secondHash[$key]) {
# add the entry, but create a new unique key to store it under first
# this example just adds a number between brackets to the key
$num = 1
do {
$newKey = '{0}({1})' -f $key, $num++
} until (!$firstHash.Contains($newKey))
# we now have a unique new key, so add it
$firstHash[$newKey] = $secondHash[$key]
}
}
else {
# no worries, the key is unique
$firstHash[$key] = $secondHash[$key]
}
}