Author Posts

June 20, 2013 at 12:13 pm

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?  


June 20, 2013 at 12:18 pm

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

June 20, 2013 at 12:22 pm

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?