The Kirkland Coder: Merge hash tables like shuffling cards.

Friday, November 30, 2012

Merge hash tables like shuffling cards.

Continuing on my work with hash tables, I have created a the new function “Merge-Hashtables”. For my own convenience I added two switches. One to remove NULLs and another to force the use of the second hash tables values when two keys match.

I have added a few examples to the function help on the use and output examples.

function Merge-Hashtables
{
    <#
    .SYNOPSIS
    Merges two hash tables with the option to remove all null key/value pairs.
     
    .DESCRIPTION
    This function will take two hash tables and merge the second hash table
    to the first. Any keys in the second hash table that exist in the 
     
    .EXAMPLE

    Merge-Hashtables $HashOne $HashTwo
    
    The basic example will merge the two hashtables not removing nulls
    and skipping existing keys from the second hashtable.
    
    Deeper Example:
    ===========================================================================
    PS C:\> $HashOne = @{One='1';Two='2';Three=$null}
    PS C:\> $HashTwo = @{Two='Two';Three='3';Four='4';Five='5'}
    PS C:\> Merge-Hashtables $HashOne $HashTwo

    Name                           Value
    ----                           -----
    Five                           5
    Two                            2
    Three
    One                            1
    Four                           4
    
    .EXAMPLE
    
    Merge-Hashtables $HashOne $HashTwo -RemoveNulValues
    
    This example removes key value pairs that have a value of NULL.
    Also it skips merging existing keys from the second hashtable.
    
    Deeper Example:
    ===========================================================================
    C:\PS> $HashOne = @{One='1';Two='2';Three=$null}
    C:\PS> $HashTwo = @{Two='Two';Three='3';Four='4';Five='5'}
    C:\PS> Merge-Hashtables $HashOne $HashTwo -RemoveNulValues

    Name                           Value
    ----                           -----
    Five                           5
    Two                            2
    One                            1
    Four                           4

    .EXAMPLE
    
    Merge-Hashtables $HashOne $HashTwo -RemoveNulValues -ForceValue
    
    This example removes key value pairs that have a value of NULL.
    Also on existing keys it updates the value with the value from
    the second hashtable.
    
    This example 
    
    Deeper Example:
    ===========================================================================
    PS C:\> $HashOne = @{One='1';Two='2';Three=$null}
    PS C:\> $HashTwo = @{Two='Two';Three='3';Four='4';Five='5'}
    PS C:\> Merge-Hashtables $HashOne $HashTwo -RemoveNulValues -ForceValue

    Name                           Value
    ----                           -----
    Five                           5
    Two                            Two
    Three                          3
    One                            1
    Four                           4

    .NOTES
    Original Author: Norman Skinner (Edgile Inc.) (v-nskin)
    Original Created on: 11/30/2012
    Version: 1.0.0.0
     
    HISTORY:
    ===========#==============#======================================
    Date       | User         | Description
    -----------+--------------+--------------------------------------
    11/30/2012 | v-nskin      | Created script
    -----------+--------------+--------------------------------------
               |              | 
    -----------+--------------+--------------------------------------
               |              | 
    -----------+--------------+--------------------------------------
               |              | 
    -----------+--------------+--------------------------------------
    #>
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true,position=0,HelpMessage= 'Enter the first hashtable to be merged into.')]
        [hashtable]
        # The hashtable to be merged into.
        $HashTable,
        [parameter(Mandatory=$true,position=1,HelpMessage= 'Enter the second hashtable to be merged into the first hashtable.')]
        [hashtable]
        # The second hash table to be merged into the first hash table.
        $HashTableToMerger,
        [switch]
        <#
            If this switch is used, any keys that exist in the first hash table will have their values updated
            with matching keys value in the second hash table.
        #>
        $ForceValue = $false,
        [switch]
        # If this switch is used, all key/value pairs with NULL values will be removed.
        $RemoveNulValues = $false
        
    )

    Set-StrictMode -Version 'Latest'
    $VerbosePreference     = 'Continue'
    $ProgressPreference    = 'SilentlyContinue'
    $ErrorActionPreference = 'Stop'

    foreach($Key in [array]$HashTableToMerger.Keys)
    {
        if ($HashTable.ContainsKey($Key))
        {
            if ($ForceValue)
            {
                # Force the value update for this key
                $HashTable[$Key] = $HashTableToMerger[$Key]
            }
        }
        else
        {
            # Add the new key value pair
            $HashTable.Add($Key, $HashTableToMerger[$Key])
        }
    }
    
    if ($RemoveNulValues)
    {
        foreach($Key in [array]$HashTable.Keys)
        {
            if ($HashTable[$Key] -eq $null)
            {
                $HashTable.Remove($Key)
            }
        }
    }

    Write-Output $HashTable
}

No comments:

Post a Comment