In Powershell you can use .Add to insert a new key/value pair into an existing hash. If the hash already contains the key, this leads to an error. The desired (by me :) behavior would be, for known keys, just udate the existing value to the provided one. I can do this with a lot of ink. Putting the .Add command in a try phrase and in the catch the changing of the value - which works fine, but the cost of ink!
Seriously, as I have this kind logic all over the place when parsing multiple configs (was this already set and needs updating or is it a new setting?), it makes for messy code:
# $msHashtable is potentially empty at this point or may not contain the key
try {
$myHashtable.Add($thisKey, $thisValue)
}
catch {
$myHashtable.$thisKey = $thisValue
}
Another issue with hashes that I have is this:
- Assume you have a hashtabel $motherOfAll which will eventually contain other hashtables, which in turn will also contain hashtables.
- Now you want to insert something into the bottommost layer of hashtables. You first need to check, that all the hashtables along the way exist and contain the proper keys.
- If not, you have to insert a bunch of empty hashtables, which get filled with another empty one... not ad infinitum of course, but still ugly. More messy code. Is there a better way?
I can provide code if needed, but I hope the issues are clear enough. As there is so much other code than the relevant pieces in my real world example, I'll restrain from posting it now...
Best,
YeOldHinnerk