If you’ve ever tried to work with PowerShell on your own, you may have found it a little bit challenging. One of the confusing things about is that some switches don’t seem like they’re doing anything for their value – which can make them difficult to remember. This article will help clear up how these switch statements are used in PowerShell and what this all means when trying to find out if something is true or false.
The “powershell switch statement multiple conditions” is a key part of PowerShell scripting. It allows for the program to be able to make decisions based on different conditions.
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”;break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content.RegExp.txt switch -regex -file.email.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content.RegExp.txt $RegExp = Get-Content “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is an email address,” $RegExp says. “[
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
-casesensitive switch (“Banana”) “Apple” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “orange” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “mango” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I have
Conditional logic is a programming idea that has been around for a long time. Conditional logic is a fancy word for checking for a condition (whether or not something occurred) and then acting on that condition.
For example, conditional logic may be used to evaluate the free space status in a script that generates a report of all disk space utilization. When conditional logic is used to assess the free disk space status, it may be marked as normal, warning, or critical based on a predetermined threshold.
The conditional logic concept is used in almost all languages, if not all. Consider the if/then expression. The switch statement is one of the conditional logic tools available in PowerShell.
You’ll discover what the PowerShell switch statement is, how it works, and how to use it in this tutorial. You’ll also discover some of the numerous ways you may employ conditional logic handling in your scripts from the PowerShell switch examples.
Understanding the Switch Statement in PowerShell
The switch statement in PowerShell is a conditional logic statement that evaluates one or more criteria. It’s similar to the If statement in PowerShell. They serve the same purpose: to test circumstances before to executing actions. Why should you use a switch statement instead of an if statement? When you need to check numerous conditions at the same time.
It might be time-consuming and tiresome to use an if statement for several conditions. Using switch statements instead of if/else statements makes evaluating many conditions easy. Please see the syntax for the switch statement below.
Switch (<test-value>) { <condition> {<action>} <condition> {<action>} }
The switch statement begins with Switch, and the value to test is surrounded in parentheses, as you can see from the syntax above (). The criteria, or case, and actions list are then placed within the curly brackets.
A value or an expression may be a condition or a case. An action may alternatively be a result that is returned or an expression that is used to perform certain activities.
The following code asks the user to enter a number. The $num variable is used to hold that number. When the test value and the condition match, the value of $num is assessed by the conditions, and the related action is executed.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
The intended result is seen below when you execute the code above in PowerShell.
To test number input, use a switch.
So, what went wrong? The $num variable’s value corresponded to a PowerShell switch case from the list of conditions (3), whose action is to display Run Action 3 on the screen.
How to Create a Default Match Clause
There are just three criteria in the switch statement below. If the $num variable’s value is 1, 2, or 3, those three conditions are true.
Switch ($num) 1 ‘Run Action 1’ 2 ‘Run Action 2’ 3 ‘Run Action 3’ $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number” $num = Read-Host “Enter a number
What if $num’s value does not meet any of the conditions? When the test value does not fit any of the requirements in that case, the code will do nothing.
When the code is performed in PowerShell and the user inputs the number 4, the result is shown below. The switch statement terminates with no result. Because there is no condition to assess the input value of 4, this is the case.
Nothing is returned by the switch test.
Instead of returning nothing, the switch statement should perform a default action when no condition is met. The default match clause comes into play in this situation.
Below is a modified version of the sample code. If the input test value does not fit any of the requirements, a default match clause is inserted at the end to show a default message. The default value is the same as the Else clause in an If statement.
Read-Host “Enter a number” $num = Read-Host “Enter a number” Change ($number) ‘Run Action 1’ is 1 ‘Run Action 2’ is 2 ‘Run Action 3’ is 3 ‘Run ‘Run Action 2’ is the second of two ‘Run Actions’. ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘Run Action 3’ 3 ‘R ‘No Action’ is the default value.
And the anticipated result is given below when the changed code is executed in PowerShell.
Default match clause in a switch statement
Multiple Test Values Evaluation
You’ve seen how to utilize the PowerShell switch statement to assess a single test value so far. The switch statement, on the other hand, may compare several test results to a set of criteria.
The code in the following example asks the user to input two digits. The switch statement then compares the two values, one by one, based on their ordinal positions.
$num1 = Read-Host “Enter first number” $num2 = Read-Host “Enter second number” $num3 = Read-H Read-Host “Enter second number” switch $num2 = Read-Host “Enter second number” switch $num2 = Read-Host “Enter ($num1), ($num2), ($num3), ($num4), ($num5) 1 “It’s the one.” 2 “It’s two.” 3 “It’s three.” 4 “It’s four.” default “Not found”
With many test values, switch
As seen in the example below, you can also provide an array as the test value for the switch expression.
switch ($arrayNum) $arrayNum = @(1,3) 1 “It’s the one.” 2 “There are two.” 3 ‘It’s three,’ says the narrator. 4 ‘It’s four,’ says the narrator. “Not found” is the default value.
Multiple Conditions Matching
The switch statement will test all conditions even after the first match is discovered, unlike the If statement, which quits after the first match is found. The switch statement now has the ability to match the test value with multiple criteria.
The test value banana matches numerous criteria inside the switch statement in the example below.
“I have an apple,” “I have an orange,” “banana,” “I have a banana,” “mango,” “I have a mango,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banana,” “banan “I don’t have that fruit,” says the default.
The test value banana matched two criteria that triggered the relevant actions, as seen in the output below.
The switch statement is used to match several criteria.
Using the Break Statement to End a Powershell Switch
You saw how the test value may match several criteria in a switch statement in the previous section. This behavior of matching several conditions may be acceptable depending on the goal of your script.
However, you may get greater control over the script if you tell the switch statement to stop running after the test value has discovered its first match. The break statement comes very handy here.
The same code as in the previous section is used in this example, but it has been updated to include the break statement. As you can see, each condition is followed by a break statement, which causes the switch statement to end when the test result matches one of the conditions.
switch (“banana”) “apple” “I have an apple”; break “orange” “I have an orange”; break “banana” “I have a banana”; break “mango” “I have a mango”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”; break “banana” “I have a banana, again!”
The following is what the output would look like if you used the code above. Only the result of the first matching condition is returned, despite the fact that there are two conditions that assess the test value “banana.”
The break statement ended the switch statement.
Exploring the Powershell Switch Statement in More Depth
The switch statement was covered in detail in the preceding sections. The switch statement, however, is more than simply the fundamentals. It’s possible that you’ll need to use it for more than simply matching basic texts and numerical values. In the following sections, you’ll learn about the many parameters or choices that the switch statement offers.
Parameters for Switch Statements
The switch statement takes five arguments. These are the parameters:
- only for string test values — This only applies to string test values. If this option is set, the condition will only be applied if the statement matches the test value precisely. The switch statement, on the other hand, acts as if the exact argument is used if this parameter is not used.
- This argument is for string test values and is case sensitive. If you provide this option, the switch statement will execute a case-sensitive match.
- regex – Using this parameter tells the switch that it will match regular expressions. Only string test values are affected by this statement.
- wildcard – This argument only works with string test values. This argument specifies that the switch statement will allow for wildcard string testing. The comparison will be made without regard to case.
- If you want to utilize the contents of a file as input instead of supplying the test value directly, use this argument. Line by line, the contents of the file will be assessed.
Each argument affects how the switch statement works. Some parameters may be combined, while some have precedence over others. The wildcard and regex parameters are incompatible. Only the last argument is utilized when both parameters are used.
Syntax of a Full Switch Statement
The lines of code following, which build on the previous section’s discussion of switch statement arguments, should appear familiar by now.
switch [-regex|-wildcard|-exact][-casesensitive] (<value>) { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> { “string”|number|variable|{ expression } { statementlist } default { statementlist } }
The string number variable expression statementlist is shown in the syntax block above. The Powershell switch statement allows text, integer, variable, and expression as test values, as indicated by that specific arrangement of words. The action(s) to perform when the condition is met are mentioned in the statementlist.
The -File parameter is used to specify a file.
The switch statement in this example utilizes the file argument to use a file as the test value input.
An example of a text file called random.txt that has a list of twenty random phrases is shown below.
She is free to live her life as she wishes, as long as she pays attention to what I have to say. As if she were a vampire, Carol swallowed the blood. He would never have entered the shower if he had known what was about to happen. The father died while the mother was giving birth. Chewing bricks, according to my dentist, is really harmful for your teeth. She could only think about individuals in need of a transplant as automobiles rushed in and out of traffic. Only if he kept the fire burning and could hear thunder in the distance would he be able to live. Even the most seasoned tourist was enthralled by the vista from the lighthouse. He had never seen a better sandcastle. We all know that as time passes, owners begin to resemble their pets more and more. He prayed his avalanche beacon’s batteries were still fresh, buried deep in the snow. Apples and oranges can’t be compared, but what about bananas and plantains? She didn’t see the irony in expecting me to change, but rather in accepting her for who she is. I have no regard for somebody who can’t distinguish between Pepsi and Coke. Dan went all the way down the rabbit hole. What is your favorite flavor of random language, on a scale of one to ten? He hated that he loved what she hated about hate. My acquaintance was slathered in baby oil. He figured a few sticks of dynamite were easier than a fishing pole to catch fish. The Japanese yen is still widely used in trade.
The code that follows will then go over each line of the random.txt file and only show the phrases that include the word “she.”
-file.random.txt switch $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $ -match’she’ $
When you execute the code above, you’ll get the following result. As you can see, only the sentences containing the word “she” are retrieved from the random.txt file’s twenty sentences.
Using the file argument as a switch statement
The -Wildcard parameter is used.
Using the same random.txt file as in the previous example, the -wildcard argument will be used to analyze the sentences in the random.txt file that include the word She. The -casesensitive argument is also used to ensure that only the word with uppercase S is returned.
switch.random.txt -casesensitive -wildcard “*She*” $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
The intended result is seen below after executing the code above. Only the phrases that fit the wildcard search for She (with an uppercase S) are returned, as you can see.
Using the WildCard and CaseSensitive arguments in a switch statement
The -CaseSensitive parameter is used in this example.
The CaseSensitive option is used in this example to do a case-sensitive search of the test value Banana. If you look carefully at the code below, you’ll see that there are two criteria for the word banana, one of which begins with an uppercase B.
switch -casesensitive (“Banana”) { “apple” { “I have $_”; break } “orange” { “I have $_”; break } “banana” { “I have $_”; break } “mango” { “I have $_”; break } “Banana” { “I have $_”; break } default { “I don’t have that fruit” } }
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
“; break “Banana” “I
The intended result of the code above is displayed below.
Using the casesenstive argument in a switch statement
The -RegEx parameter is used.
The -RegEx argument is used in this example to do a regular expression match to see whether the test result is an email address.
The regular expression that will be utilized to assess the test value is shown below. RegExp.txt is the name of the file where this regular expression is stored.
(?:[a-z0-9!#$%&’+/=?^_{|}~-]+(?:.[a-z0-9!#$%&’*+/=?^_{|}~-]+)|”(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|[x01-x09x0bx0cx0e-x7f])”)@(?:(?:a-z0-9?.)+a-z0-9?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-][a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|[x01-x09x0bx0cx0e-x7f])+)])
The following is a list of allegedly legitimate email addresses. This list is preserved in the email.txt file.
The first line of the code below imports the contents of the RegExp.txt file and stores it in the $RegExp variable. Then, as specified by the -file argument, the Powershell switch statement utilizes the email.txt file as the input for test values.
$RegExp = Get-Content .RegExp.txt switch -regex -file .email.txt { $RegExp {“[$_] is an email address”} Default {“[$_] is NOT an email address”} }
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
] is NOT an email address” is the default.
Only the test value that matches the regular expression contained in the $RegExp will be verified when the code above is performed in PowerShell. The Default clause would be activated if the test value did not match the regular expression. Take a look at the example output below.
Validating email addresses using Switch RegEx
Conclusion
You learnt the fundamentals of the switch statement and how to use it to assess conditions before executing any associated code in this article. More complicated tests, such as assessing regular expressions and wildcards, may be performed using the switch statement.
The parameters may also be combined to provide a more controlled effect by combining their functionality. I hope you’ve acquired a new tool in your PowerShell arsenal as a result of this post for when you need to develop scripts with conditional logic and decision making.
Perhaps your next project will be to use the switch statement to develop a script that reports unhealthy systems or monitors event logs. The PowerShell switch statement may be used in a variety of ways, so keep practicing.
Good luck with your scripting!
Additional Reading
The “powershell switch fall through” is a PowerShell feature that allows you to use the case statement in your scripts. The case statement will allow you to decide which branch of the switch statement to execute based on the value of one or more variables.
Frequently Asked Questions
What is PowerShell switch statement?
A: A PowerShell switch statement is a type of conditional expression that lets you choose from multiple possible values using a structured ternary operator. It allows for simple control flow and error handling in your scripts, without the need to use different commands like if else or do { } while loops.
What is switch type in PowerShell?
A: Switch type is a PowerShell cmdlet that allows you to build and manage an array of multiple switch, string or boolean values.
How do you write a switch in PowerShell?
A: There are a few different ways. It is easiest to use the switch keyword in PowerShell, but you can also use case statements or if/else blocks.
Related Tags
- powershell switch case multiple values
- powershell switch parameter
- powershell switch default value
- powershell switch between values
- powershell switch default not working