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.
[cc lang=”powershell”]$colorCodes = Import-Csv ColorCodes.csv[/cc]

Define a hashtable object:
[cc lang=”powershell”]$colorCodeHT = @{}[/cc]

Examples for adding to a hashtable:
[cc lang=”powershell”]
# 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
[cc lang=”powershell”]
# Using square brackets, just like the above ‘add’ example
$colorCodeHT[‘Red’] = ‘#123456’

Examples for removing from a hashtable:
[cc lang=”Powershell”]
# Remove a single item by key

# Remove all of the entries from the hashtable:

This entry was posted in Scripting. Bookmark the permalink.

Leave a Reply

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