Switch Statement with hash table

This topic contains 2 replies, has 2 voices, and was last updated by  markdjones82 4 years, 5 months ago.

  • Author
    Posts
  • #7652

    markdjones82
    Participant

    All,

    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

    Don Jones
    Keymaster

    $_ 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

    markdjones82
    Participant

    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?

You must be logged in to reply to this topic.