Поделиться через


How-to: For-each for Hash Tables in PowerShell

Have you ever encountered a situation where you may need a dynamic array – perhaps because you’re working with an undetermined number of objects, or collections of objects that don’t all look the same or aren’t the same type?  When this happens to me, I typically switch gears and use a hash table.

This can be done quite easily by using the following PowerShell syntax:

Next, I’ll just go and populate the hash table with a few simple values

Now, we can check the value of $HashTable, and we should return something like this

Now for the fun part.  Since we’re all used to working with arrays, and the HashTable kind of looks and feels like an array (it’s not an array), it’s pretty natural for us to think: “Hey, I’ll just go grab the first item in the array by using $HashTable[0].  This is what you’ll get if you do that

If we want to reference a specific item in a Hash Table, we have to reference the key.  How do we get the key, you might ask?  like this

So, if I want to return the value of the item in the Hash Table with the key named “GitHubProcesses”, I would do this

So, what does that have to do with for-each  for Hash Tables?  Simple.  We can get a list of keys, and we need those keys if we want to get values.  So you can simply iterate through all keys in the Hash Table and get the value of each key, like this

And that would produce an output like this

So the next question would be: what happened to that nice task list that I had before?  And that all comes down to knowing the type of data you’re working with.  In that case, we have stored an array into the value of the GitHubProcesses key, and we have stored a string into the value of the Roger key.  We can verify this pretty easily

This will produce the following output

So, knowing the type of data you are working with is also important.  In the previous case, the array was being output as an array of entries, as opposed to the value of those entries, whereas the string was cleanly being displayed as the value of the string.  We could have simply chosen not to use write-host, so that the array would be expanded, like so

This would provide the following output

Summary

Long story short, the key, literally, is the key to working with Hash Tables..  Once you’ve mastered that, you can then start implementing advanced logic, such as detecting the object type, or well, anything other than simply outputting the value to the console.

Feedback

As always, should you have any feedback, feel free to post in the comments below.

You can also reach me on twitter @RCormier_MSFT