functions/Merge-ConfigHashtables.ps1

<#
.SYNOPSIS
    This function merges configuration hash tables.
.DESCRIPTION
    This function accepts multiple hash tables from the pipeline and merges
    each one into a single hash table which is returned.
    Duplicate keys across the input hash tables will cause an exception to be thrown.
.PARAMETER HashTable
    One or more hash tables to be merged.
.EXAMPLE 1
    PS C:\> $ConfigurationData = $psDeployConfigurationData, $dscConfigurationData | Merge-Hashtables
     
    This example pipes two config hash tables into the function and assigns the output to a third.
#>

function Merge-ConfigHashtables {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)] 
        [HashTable] 
        $HashTable
    )
    
    begin {
        Write-Information "Beginning merging config hash tables"
        $Output = @{}
    }
    
    process {
        $HashTable.GetEnumerator() | Sort-Object $_.Key | ForEach-Object {
            $key = $_.Key

            Write-Debug "Processing key $key"
            if ($Output.ContainsKey($key)) {
                if ($Output.$key -is [HashTable]) {
                    Write-Debug "Output hashtable contains key '$key', merging hash tables"
                    $Output.$key = $Output.$key, $hashTable.$key | Merge-ConfigHashtables
                }
                elseif ($Output.$key -is [Array]) {
                    Write-Debug "Output hashtable contains key '$key', merging arrays"
                    $Output.$key = $Output.$key, $hashTable.$key | Merge-ConfigArrays
                }
                else {
                    Write-Error "Output hashtable contains key '$key', you cannot override variables!"
                    throw
                }
            }
            else {
                Write-Debug "Output hash does not contain key '$key' - straight copy"
                $Output.$key = $hashTable.$key
            }
        }
    }
    
    end {
        Write-Information "Ending merging config hashtables"
        $Output
    }
}