Windows Powershell Switch Loop _powershell

Source: Internet
Author: User
Tags foreach arrays switch loop

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.