Learn

switch statements provide similar behavior as if/elseif statements, but the syntax is more straightforward, making the logic easier to implement in your code:

$myVar = 5 switch ($myVar) { 10 { Write-Host "It is 10" } 5 { Write-Host "It is 5" } default { Write-Host "Some other number" } }

This example starts with the switch keyword followed by a value to test, $myVar. Inside the switch body test expressions, 10 and 5, are each compared to $myVar in order. The body inside the curly brackets is executed if any values are equal. Lastly, the default value acts as an else statement, where the code is executed if no given value is equal to $myVar.

Conditional expressions can be used within the switch body to create more complex testing:

$myVar = 5 switch ($myVar) { {$_ -gt 5} { Write-Host "Greater than 5" } {$_ -lt 5} { Write-Host "Less than 5" } default { Write-Host "It is 5" } }

Each test expression is now enclosed in curly brackets, with $_ representing $myVar. If the expression result is true, the enclosed code run. In the example above, both written test expressions {$_ -gt 5} and {$_ -lt 5} are false, so the default code is run.

It is important to note that if one of the defined conditions, {$_ -gt 5}, is true, the following conditions are still checked.

$myVar = 10 switch ($myVar) { {$_ -gt 5} { Write-Host "Greater than 5" } {$_ -gt 0} { Write-Host "Greater than 0" } }

The above code will output the following:

Greater than 5 Greater than 0

This differs from if and elseif because all the conditions are still tested even if the first condition is true. We will look at a command that allows us to break out of the switch statement once a condition is true.

Instructions

1.

Use a switch statement to check the value of $var. Inside the switch body create a condition to check if $var is equal to 5 and run Write-Host with some output.

2.

Add a condition at the end of the switch body that tests for $var is less than 0 and an output statement using Write-Host.

3.

Add another condition at the end of the switch body that tests for $var is greater than 0 and an output statement using Write-Host.

4.

Add a default statement at the end of the switch body with an output statement using Write-Host.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?