The Kirkland Coder: Remove item from a hashtable.

Friday, November 30, 2012

Remove item from a hashtable.

I had an issue removing nulls values from hashtables Key/Value pair. So I wrote a function to make quick work of it.

By converting the hasktables key collection to an array, I do not get an error removing key/value pairs while iterating over the hash.

function Remove-HashtableNulls
{
    <#
    .SYNOPSIS
    Removes any Key pairs that have a NULL value.
     
    .DESCRIPTION
    This function will take a hashtable and iterate over all the
    Key pairs and remove any that have a NULL for the value. It 
    will then return the edited hashtable.
     
    .EXAMPLE
    PS C:\> $TestHash = Remove-HashtableNulls $TestHash
 
    .EXAMPLE
    PS C:\> $TestHash = Remove-HashtableNulls -HashTable $TestHash
 
    .NOTES
    Original Author: Norman Skinner (Edgile Inc.) (Norman.Skinner@Edgile.com)
    Original Created on: 11/30/2012
    Version: 1.0.0.0
     
    HISTORY:
    ===========#================#======================================
    Date       | User           | Description
    -----------+----------------+--------------------------------------
    11/30/2012 | Norman Skinner | Created script
    -----------+----------------+--------------------------------------
               |                | 
    -----------+----------------+--------------------------------------
    #>
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true, HelpMessage= 'Enter a hashtable for null removals.')]
        [hashtable]
        # The hashtable that will have any null valuses removed.
        $HashTable
    )
 
    Set-StrictMode -Version 'Latest'
    $VerbosePreference     = 'Continue'
    $ProgressPreference    = 'SilentlyContinue'
    $ErrorActionPreference = 'Stop'
 
    foreach($Key in [array]$HashTable.Keys)
    {
        if ($HashTable[$Key] -eq $null)
        {
            $HashTable.Remove($Key)
        }
    }
    
    Write-Output $HashTable
}

No comments:

Post a Comment