Learn the Basics of PowerShell Hash Tables

Learn the Basics of PowerShell Hash Tables

  • Comments 5
  • Likes

Summary: Microsoft Scripting Guy Ed Wilson covers the basics of hash tables in Windows PowerShell.

 

Hey, Scripting Guy! QuestionHey, Scripting Guy! I have been reading your articles for several years, but I have never been compelled to write until today. I was reading an old article about putting all the Windows PowerShell cmdlet aliases into a hash table, and suddenly it dawned on me I do not know what a hash table really is. I did a search, using Bing for hash table, and I can tell you I got all kinds of really weird stuff coming back for results. Then it dawned on me, I would try to use help. Well, I typed help hash-table and believe it or not, an article about Get-WinEvent opened. As you can imagine I was becoming frustrated and decided to go right to the horse’s mouth so to speak, and ask the Scripting Guys. So I guess my question is, “What in the world is a hash table?” I eagerly await your exalted pearls of wisdom and remain your faithful reader.

—BW

 

Hey, Scripting Guy! Answer Hello BW,

Microsoft Scripting Guy Ed Wilson here. It is the Fourth of July in Charlotte, North Carolina, in the United States. The sun is shining, and the humidity is rising. The Scripting Wife and I are planning on watching a fireworks celebration later this evening, but we will probably do so from the comfort of our air-conditioned house. We are lucky in that we can generally see fireworks that are launched from the nearby lake front. We do not get to see them as they immediately leave the ground, but for most of their trek skyward, we can watch. Of course, the resulting plumage is very visible. The tradeoff for missing a few seconds of the fireworks is we miss all the traffic, congestion, heat, and mosquito bites. I think it is an even trade (and the Scripting Wife seems to agree). Anyway, as I mentioned yesterday, the Scripting Wife and I are more accidental fireworks watchers.

BW, I was really curious when you said you typed help hash-table and got back an article about Get-WinEvent. The reason is because you have accidently run across a feature of the Get-Help cmdlet. I know what you are thinking: “Microsoft always says that is not a bug, but is a feature.” In this case, I am telling the truth, and the feature is actually documented in the Help files. If you type get-help get-help and look in the Description portion of the results, you will see that the Get-Help cmdlet does more than simply match cmdlet names. There are actually rules that govern this behavior. The rules are listed here:

  1. Exact match with cmdlet or help topic—displays the contents of the help file.
  2. A word or pattern match that is unique to a help topic title—displays the contents of the help file.
  3. A word or pattern match that matches several help topic titles—displays a list of matching titles.
  4. A word that does not appear in any help topic title—displays a list of topics that include that word in their contents.

This means that if you want to find a listing of Windows PowerShell cmdlets that include the computername parameter, you can easily find them by typing Get-Help computername. Pretty cool, huh?

BW, a hash table is a data structure that is used to temporarily store data. The data structure is made up of a series of unique keys and their associated values. In this way, you could think of a hash table as a Microsoft Excel spreadsheet that is made up of two columns. The first column includes a certain number of rows. The contents of the cells that make up the first column are unique within that column. The second column is made up of the same number of rows, but the items in the cells do not need to be unique. This is illustrated in the following figure.

Image of the hash table and its contents

To create a hash table requires the use of the @ symbol, and a pair of braces (curly brackets)—“{}”. Inside the curly brackets, the first item listed is the key, and the second item listed is the value. The syntax appears in the following table.

 

Variable Name

Equality operator

At sign

Open  Brace

Key value

Equality operator

Value value

Close Brace

$hash

=

@

{

“key”

=

“value”

}

 

The use of the above syntax is illustrated by the code that follows. The first line of code creates the hash table and stores it in a variable named $hash. The second line of code displays the contents of the $hash variable. The remaining lines are used to display the values stored in the $hash variable.

PS C:\Users\ed.WOODGROVE> $hash = @{"key" = "value"}

PS C:\Users\ed.WOODGROVE> $hash

 

Name                           Value

----                           -----

key                            value

 

BW, now that you have a hash table stored in the $hash variable, pipe it to the Get-Member cmdlet so that the members of the object are displayed on the Windows PowerShell console. This technique follows along with its accompanying output.

PS C:\Users\ed.WOODGROVE> $hash | Get-Member 

 TypeName: System.Collections.Hashtable

 

Name                           MemberType                 Definition

----                               ----------                        ----------

Add                              Method                         System.Void Add(System.Object key, System.Object value)

Clear                             Method                         System.Void Clear()

Clone                            Method                         System.Object Clone()

Contains                        Method                         bool Contains(System.Object key)

ContainsKey                   Method                         bool ContainsKey(System.Object key)

ContainsValue                Method                         bool ContainsValue(System.Object value)

CopyTo                         Method                         System.Void CopyTo(array array, int arrayIndex)

Equals                           Method                         bool Equals(System.Object obj)

GetEnumerator              Method                         System.Collections.IDictionaryEnumerator GetEnumerator()

GetHashCode                Method                         int GetHashCode()

GetObjectData               Method                         System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo inf...

GetType                        Method                         type GetType()

OnDeserialization           Method                         System.Void OnDeserialization(System.Object sender)

Remove                         Method                         System.Void Remove(System.Object key)

ToString                        Method                         string ToString()

Item                              ParameterizedProperty      System.Object Item(System.Object key) {get;set;}

Count                            Property                        System.Int32 Count {get;}

IsFixedSize                     Property                        System.Boolean IsFixedSize {get;}

IsReadOnly                    Property                        System.Boolean IsReadOnly {get;}

IsSynchronized               Property                        System.Boolean IsSynchronized {get;}

Keys                              Property                        System.Collections.ICollection Keys {get;}

SyncRoot                       Property                        System.Object SyncRoot {get;}

Values                           Property                        System.Collections.ICollection Values {get;}

 

From the above output, an add method appears with the following signature (definition).

Add(System.Object key, System.Object value)

This tells me that the add method takes two values. The first value is a key, and the second one is a value. Both of these input values are objects. The following code illustrates adding an additional key/value pair to the hash table stored in the $hash variable. The first line of code adds the new key/value pair to the hash table. The second line of code displays the contents of the hash table. One thing to keep in mind is that when the hash table was first created, the equality operator was used with the syntax of key=value. But when calling the add method, a comma is used to separate the two values. The code and the accompanying output are shown here:

PS C:\Users\ed.WOODGROVE> $hash.Add("secondkey", "second value")

PS C:\Users\ed.WOODGROVE> $hash

 

Name               Value

----                   -----

Secondkey         second value

Key                   value

 

To remove an item from the hash table, use the remove method and pass it the key value. The signature of the remove method is shown here:

Remove(System.Object key)

The following code illustrates removing the secondkey and its accompanying value from the hash table stored in the $hash variable. The second line of code displays the contents of the hash table.

PS C:\Users\ed.WOODGROVE> $hash.Remove("secondkey")

PS C:\Users\ed.WOODGROVE> $hash

 

Name               Value

----                   -----

Key                   value

 

BW, that should help you start using hash tables in your scripts. Hash Table Week will continue tomorrow when I will talk about creating a hash table on the fly inside a script.
 

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

 

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Hey Ed,

    is this a week about Powershell data structures?

    In fact a hash table is an essential frequently used data structure that should be well understood by every PS scripter. So I can only strongly advice to "know your enemy" because

    you can hardly live without it if you want to effectively work with Powershell.

    Klaus

  • Hi Klaus-

    Yes, this week  I am going to spend the entire week talking about Hash Tables. I agree with your statement that it is a frequently used data structure that should be understood by every PowerSheller ...

    ed