PowerShell – Hash Table Get That Value


When writing scripts I like to use PowerShell ISE or VSCode a lot. It simplifies a lot of your daily scripting tasks like IntelliSense or Snippets. But sometimes these little helper don’t tell always the truth. Why? Well, I show you an example which is quite common.

On problem there is if you are working with hash tables is that you have a key value pair and you would like to retrieve a value for a specific key. Like in this example I want to retrieve the value for Key2…

 $Hash = @{Key1 = "Value1";Key2 = "Value2"}

If you check the the IntelliSense of $Hash, you could use…


…this would output Value2, that’s correct. But what if you have a hash table and you would like to “search” for a specific key?

Well, if we expose the members using Get-Member we see something like this…


There isn’t anything that could help, so we add a little special power to the Get-Member command using –Force, we receive a lot more info…


One very interesting method to our problem seems the “hidden” Get_Item() method, if we try something like…


…we will receive the corresponding value “Value2”

How does this help? Well you could easily replace the “Key2” string through a variable if needed.

Update 13.04.2018: Or you could use $Hash[$Variable] for using variables. Thank you @rd_bartram!

If you need to change the value of “Key2” you can just use the Set_Item() method like this…

Hash.Set_Item("Key2", "Value3")

Now the new value is “Value3”.

As you can see it is easily possible to discover new members using Get-Member –Force and if you need to discover a value for a specific key in a hash table use the Get_Item() method.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.