Merging hashtables in PowerShell: how?

前端 未结 12 1918
猫巷女王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:07

    In case you want to merge the whole hashtable tree

    function Join-HashTableTree {
        param (
            [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
            [hashtable]
            $SourceHashtable,
    
            [Parameter(Mandatory = $true, Position = 0)]
            [hashtable]
            $JoinedHashtable
        )
    
        $output = $SourceHashtable.Clone()
    
        foreach ($key in $JoinedHashtable.Keys) {
            $oldValue = $output[$key]
            $newValue = $JoinedHashtable[$key]
    
            $output[$key] =
            if ($oldValue -is [hashtable] -and $newValue -is [hashtable]) { $oldValue | ~+ $newValue }
            elseif ($oldValue -is [array] -and $newValue -is [array]) { $oldValue + $newValue }
            else { $newValue }
        }
    
        $output;
    }
    

    Then, it can be used like this:

    Set-Alias -Name '~+' -Value Join-HashTableTree -Option AllScope
    
    @{
        a = 1;
        b = @{
            ba = 2;
            bb = 3
        };
        c = @{
            val = 'value1';
            arr = @(
                'Foo'
            )
        }
    } |
    
    ~+ @{
        b = @{
            bb = 33;
            bc = 'hello'
        };
        c = @{
            arr = @(
                'Bar'
            )
        };
        d = @(
            42
        )
    } |
    
    ConvertTo-Json
    

    It will produce the following output:

    {
      "a": 1,
      "d": 42,
      "c": {
        "val": "value1",
        "arr": [
          "Foo",
          "Bar"
        ]
      },
      "b": {
        "bb": 33,
        "ba": 2,
        "bc": "hello"
      }
    }
    

提交回复
热议问题