Hashtables: Introduction

I was recently working on a script for a co-worker who is trying to learn more powershell. In the script I had used a couple of hashtables to store information…which caused a couple of questions as he was reviewing the code. This post is an introduction to powershell hashtables.

A hashtable stores indexed key-value pairs in memory and is similar to the vbscript dictionary object. To help describe these concepts, I have listed a few examples based on a CSV file containing HTML color codes.

The examples below will:
1.) Import the CSV into a powershell array object,
2.) Show how to use the array object to return a specific code given a color name
3.) Convert the object from step 1 into a hashtable
4.) Show how to use the hashtable to return a specific code given a color name

[cc lang=”Powershell”]
# Example 1:
$colorCodes = Import-Csv ColorCodes.csv

# Example 2:
# Using just the array object created from Import-CSV
# we can select the color code for Red with just one line
($colorCodes | Where-Object {$_.ColorName -eq ‘Red’}).Code

# Example 3:
# We could also create a hash table and store each item
# from the array using a couple lines of code
$colorCodeHT = @{}
$colorCodes | %{ $colorCodeHT.Add($_.ColorName, $_.Code) }

# Example 4
# And then we can retreive the code for red using either of the
# examples below. Note: you only need one as they return the same
# value. The first sample is my preferred method, but either works.

This entry was posted in Scripting. Bookmark the permalink.

Leave a Reply

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


Notify me of followup comments via e-mail. You can also subscribe without commenting.