Handle multiple if statements

Brief Syntax

      Switch ($item)
       value { expression }
       value { expression }

Full Syntax

      Switch [ -regex | -wildcard | -exact ] [-casesensitive ] ( pipeline )
        "string"|number|variable| { expression } { statementlist }
        default { statementlist } 

      Switch [ -regex | -wildcard | -exact ] [-casesensitive ] -file filename
        "string" | number | variable | { expression } { statementlist }
        default { statementlist } 

   -regex       Treat the match clause, if a string, as a Regex.

   -wildcard    Treat the match clause, if a string, as a wildcard string
                Wildcard characters:
                    ?   = Any single unspecified character.
                    *   = Zero or more unspecified chars.
                  [a-b] = Any character in the range a-b
                  [ab]  = The specified characters.
                The wildcard match is case in-sensitive 

   -exact	     Match strings exactly (disable wildcards)

 -casesensitive Modify the match clause, if a string, to be case sensitive

   -file        Take input from a file (or representative)

The switch options can be given in abbreviated format using the first letter, so -e is equivalent to -exact

The keyword break indicates that no more processing will occur and the switch statement will exit.

The keyword continue indicates that no processing will continue against the current token and the next token in the conditional will be evaluated. If no tokens are available, the switch statement will exit.

If pipeline results in an array, each element of the array will be evaluated in ascending offset order (starting at 0). At least one element must be present that meets at least one condition or an error will result.


Compare a string, this is effectively just a string of IF statements:

 PS> $my_variable = "ss64"
 PS> switch ($my_variable){
     ss61 {"First result"; break}
     ss62 {"Second"; break}
     ss63 {"Third"; break}
     ss64 {"Fourth"; break}
     ss65 {"Fifth"; break}
     default {"Something else happened"; break}

The break at the end of each condition tells the switch to stop looking further, if you omit this, the switch statement can match more than one clause and perform more than one action.

"History teaches us that men and nations behave wisely once they have exhausted all other alternatives" ~ Abba Eban


Break statement
Continue statement
ForEach-Object - (foreach) Loop for each object in the pipeline
ForEach - Loop through values in the pipeline
For - Loop through items that match a condition
IF - Conditionally perform a command
While - Loop while a condition is True

© Copyright SS64.com 1999-2014
Some rights reserved