In PowerShell, a switch
statement is a type of control flow statement that allows you to specify a list of values, and then choose one of several code blocks to execute based on the value that matches the specified input.
This allows you to write cleaner and more efficient code, by avoiding long chains of if-else
statements.
Here's an example of a switch
statement in PowerShell:
$input = "Hello World"
switch ($input) {
"Hello World" {
Write-Output "The input is 'Hello World'"
}
"Goodbye World" {
Write-Output "The input is 'Goodbye World'"
}
default {
Write-Output "The input is something else"
}
}
In this example, the switch
statement starts by defining the $input
variable with the value Hello World
. The switch keyword is followed by the $input
variable in parentheses, which specifies the input that will be used to determine which code block to execute.
The switch
statement contains three code blocks, each starting with a value in quotes:
Hello World
.Goodbye World
.In this example, the switch statement will execute the first code block, which contains the Write-Output
cmdlet. This cmdlet will output the message The input is 'Hello World'
to the console.
You can also use the switch statement to match multiple values with a single code block.
Here's an example:
$input = "Hello"
switch ($input) {
"Hello" -or "Hi" -or "Howdy" {
Write-Output "The input is a greeting"
}
default {
Write-Output "The input is something else"
}
}
In this example, the switch
statement starts by defining the $input
variable with the value Hello
. The switch
keyword is followed by the $input
variable in parentheses, which specifies the input that will be used to determine which code block to execute.
The switch
statement contains two code blocks:
Hello
, Hi
, and Howdy
. The -or
operator is used to specify multiple values that will match the same code block.In this example, the switch
statement will execute the first code block, which contains the Write-Output
cmdlet. This cmdlet will output the message The input is a greeting
to the console.
The switch statement is a useful tool in PowerShell for choosing one of several code blocks to execute based on a specified input value. It allows you to write cleaner and more efficient code, by avoiding long chains of if-else statements.
Related tutorials curated for you
How to move items in PowerShell
How to print output in PowerShell
What is PowerShell Grep?
How to get the current directory in PowerShell
How to exclude multiple folders using Get-ChildItem in PowerShell
How to rename a computer in PowerShell
String formatting in PowerShell
Boolean literals in PowerShell
How to install PowerShell on Mac
What is `ls` for PowerShell?
Using -Or in PowerShell
How to create an alias in PowerShell