Switch

The switch statement is also a conditional statement, and can handle many types of conditions. You should make use of it when you want to check multiple conditions at once. The basic syntax looks as follows:

Switch (<test-value>) 
{
<condition> {<action>}
<condition> {<action>}
}

It starts with the switch keyword, followed by the value that you want to test and validate the conditions on. Then, the curly braces follow, with a variable number of conditions. Each condition will handle one scriptblock. This scriptblock can be a single line or a complete, multilined script:

# Simple example
switch (42)
{
1 {"It is one."}
2 {"It is two."}
42 {"It is the answer of everything."}
}

# "It is the answer of everything."

You can add various numbers of input values, as shown in the following example:

# Simple example - various input values
switch (42, 2)
{
1 {"It is one."}
2 {"It is two."}
42 {"It is the answer of everything."}
}
# "It is the answer of everything."
# "It is two."

In addition, the switch statement also accepts RegEx and wildcards:

#example using Regex
switch -Regex ("fourtytwo")
{
1 {"It is one."; Break}
2 {"It is two."; Break}
"fo*" {"It is the answer of everything."}
}
# "It is the answer of everything."
The switch statement can easily implement complex conditions. Further examples are demonstrated at: https://kevinmarquette.github.io/2018-01-12-Powershell-switch-statement/.

In addition, it is strongly recommended to dive into RegEx, as they are very handy for many use cases. Due to their complexity, they are not included in this book. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset