PowerTip: Find Value from PowerShell Hash Table


Summary: Look up values from a Windows PowerShell hash table.

Hey, Scripting Guy! Question How can I look up a specific value that is associated with a specific key in a Windows PowerShell hash table?

Hey, Scripting Guy! Answer Use the Item method and supply the key, for example:

$hash = @{

   2 = "Removable disk"

   3="Fixed local disk"

   4="Network disk"

   5 = "Compact disk"}

 

$hash.Item(3)

Comments (7)

  1. tommymaynard says:

    @Adrian Rodriguez – There is a compatibility issue when using dotted notation in PowerShell 2.0; however @DaWho, there is not when using the square brackets.

    When using square brackets to reference the name, with this hash table in particular, it’s good to remember that you’re not referencing an index number as if this were a standard array. That’s what this usage looks like and could be confusing for others looking
    over your script. If the numeric numbers 1, 2, 3, and 4 where replaced with one, two, three, and four, then you can return the value using $hash.four (PS 3.0 and greater), $hash[‘four’], or $hash.Item(‘four’).

  2. Adrian Rodriguez says:

    Is there a disadvantage (or capatability issue) to simply using $hash.3?

  3. DaWho says:

    How about:
    $hash[4]

  4. SaMolPP says:

    hi,
    i am having a key value pair
    like :
    wrongPageTitle1:CorrectPagetitle1
    wrongPageTitle2:CorrectPagetitle2
    wrongPageTitle3:CorrectPagetitle3
    wrongPageTitle4:CorrectPagetitle4

    is there any way i can iterate through the above key value pair and get the value of each key
    like :
    if i use foreach loop : for key called "wrongPageTitle1" i wnat to retrieve the value which is "CorrectPagetitle1"

    should i declare the above in a hash and iterate it?
    help is appreciated!

  5. Randy Schwartz says:

    A little bit late, maybe helpful anyway:

    foreach ($item in $hash.GetEnumerator() | Sort Name) {
    Write-Output ("Key: {0} – Value: {1}" -f $item.name, $item.value)
    }

  6. Shaan114 says:

    $map=@{}
    $map.add(“a”,1)
    $map.add(“b”,2)
    $map.add(“c”,3)
    $map.add(“d”,4)
    foreach(key in $map.keys)
    {
    fun $key , $map[$key]
    }
    here fun is wmi-method . I ma getting “cannot convert System.object to System.string ” error please suggest me what can i do.

    1. SunilM says:

      Kinda late but I think you forgot to put a $ in front of key (foreach ($key in $map.keys))

Skip to main content