The switch is a multiple-branch keyword, but it can be used for loop processing because the switch supports collections in PowerShell. Here are two examples.
The first converts a foreach loop into a switch loop:
Copy Code code as follows:
#使用Foreach循环
$nums =10..7
foreach ($n in $nums)
{
"N= $n"
}
n=10
N=9
N=8
N=7
#使用Switch循环
$nums = 10..7
Switch ($nums)
{
Default {"N= $_"}
}
n= 10
N= 9
N= 8
N= 7
Sometimes the processing of the set, in the loop, the condition to be judged, the use of switch loops can be in place, for example:
Copy Code code as follows:
$nums = 10..7
Switch ($nums)
{
{($_% 2)-EQ 0} {"$_ even"}
{($_% 2)-ne 0} {"$_ cardinality"}
}
10 Even
9 Base
8 even
7 base
PowerShell arrays and switch statements, arrays in PowerShell can be combined with switch statements to produce unexpected results.
Arrays in PowerShell can be combined with switch statements to produce unexpected results.
First look at the example:
Copy Code code as follows:
$myArray = 1,5,4,2,3,5,2,5
Switch ($myArray) {
1 {' One '}
2 {' Two '}
3 {' Three '}
4 {' Four '}
5 {' Five '}
}
All of the elements in the array are in 1,2,3,4,5 this range. Use a switch statement to translate each number into one.
Automatically outputs after the switch, so the end result is:
Copy Code code as follows:
One
Five
Four
Two
Three
Five
Two
Five
This is a very novel effect, first recorded here, there is a need to dig deeper in the back.