When you need to check the multiple conditions in PowerShell, we must use the Switch statement.
This statement in PowerShell is equivalent to the series of ‘If‘ statements, but it is simple to use. This statement lists each condition and the code of block associated with each condition. If a condition is ‘True‘, then the block of code is executed with that particular condition.
Syntax of Switch Statement
The following are the rules apply to the switch statement:
- The default statement is optional. Even if this statement does not have a default statement, it would execute without any problem.
- The test_expression can be a logical or an integer expression.
- If a break statement is applied to any case, then the switch statement is terminated by the break statement after that case.
Flowchart of Switch Statement
The following examples describe how to use the switch statement:
Example 1: In this example, the value of the day matches one of the numeric values.
The day is Tuesday
Example 2: In this example, we check that the value of the variable is either a 10, 50 or 100. If none of these value matches, then the default statement is executed.
The Number is not equal to 10, 50, and 100.
Example 3: In this example, we illustrate how to use the switch statement with the array as an input:
April You give a Wrong number