Merging hashtables in PowerShell: how?

前端 未结 12 1915
猫巷女王i
猫巷女王i 2021-01-07 18:26

I am trying to merge two hashtables, overwriting key-value pairs in the first if the same key exists in the second.

To do this I wrote this function which first remo

12条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 19:17

    I see two problems:

    1. The open brace should be on the same line as Foreach-object
    2. You shouldn't modify a collection while enumerating through a collection

    The example below illustrates how to fix both issues:

    function mergehashtables($htold, $htnew)
    {
        $keys = $htold.getenumerator() | foreach-object {$_.key}
        $keys | foreach-object {
            $key = $_
            if ($htnew.containskey($key))
            {
                $htold.remove($key)
            }
        }
        $htnew = $htold + $htnew
        return $htnew
    }
    

提交回复
热议问题