Switch Statement with hash table

Welcome Forums General PowerShell Q&A Switch Statement with hash table

This topic contains 2 replies, has 2 voices, and was last updated by

5 years, 7 months ago.

  • Author
  • #7652

    Points: 0
    Rank: Member


    I had a question in regards to the switch statement and hash tables.  I know with a switch statement you can do an array like so

    $a = 21, 38, 6
    switch ($a) 
            1 {"The color is red."} 
            2 {"The color is blue."} 
            3 {"The color is green."} 
            4 {"The color is yellow."} 
            5 {"The color is orange."} 
            6 {"The color is purple."} 
            7 {"The color is pink."}
            8 {"The color is brown."} 
    I actually have found an example that I use to evaluate a hash table based on the $_.name value
    $myHash = @{}
    $myHash["a"] = 1
    $myHash["b"] = 2
    $myHash["c"] = 3
    switch ($myhash.GetEnumerator())
    {$_.name -like ‘*a*’ }    {"It is a"} 
    What I want to understand is how does the curly braces know to do a comparison on the $_.name variable?  
  • #7656

    Points: 1,785
    Helping HandTeam Member
    Rank: Community Hero

    $_ gets populated with whatever's in the switch construct's parentheses. The comparison being in curlies makes it a script block, which PowerShell executes and looks for True or False.

  • #7657

    Points: 0
    Rank: Member

    Ah ok, so within the switch statement you can have a code block for the match as opposed to a static value?

    Last question, how come I don't need to put Where {$_.name -eq "a"}?  Is the Where assumed on that comparison?

The topic ‘Switch Statement with hash table’ is closed to new replies.