Hashtables: Adding, Updating and Removing Items

To help describe these concepts, I have listed a few examples based on a CSV file containing HTML color codes.

For purposes of sample data, create an array object of colors and HTML color codes.

$colorCodes = Import-Csv ColorCodes.csv

Define a hashtable object:

$colorCodeHT = @{}

Examples for adding to a hashtable:


# For the old vbscripter (this is the method I use)
# $colorCodeHT.Add('key','value')
$colorCodes | %{$colorCodeHT.Add($_.ColorName, $_.Code)}

# For the person who likes equal signs
# $colorCodeHT['key'] = 'Value'
$colorCodes | %{$colorCodeHT[$_.ColorName] = $_.Code}

Examples for updating existing entries


# Using square brackets, just like the above 'add' example
$colorCodeHT['Red'] = '#123456'

Examples for removing from a hashtable:


# Remove a single item by key
$colorCodeHT.Remove('Red')

# Remove all of the entries from the hashtable:
$colorCodeHT.Clear()
This entry was posted in Scripting. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *