Changes

Jump to: navigation, search

The Windows PowerShell 1.0 switch Statement

2,322 bytes added, 16:52, 3 December 2008
Using switch Statements to Iterate Through Ranges and Collections
== Using switch Statements to Iterate Through Ranges and Collections ==
 
So far in this chapter we have looked at using switch statements to find matches to a single value. In fact, Windows PowerShell switch statements can be used to iterate through collections of values. A simple example involves a number range:
 
<pre>
switch (1..10)
{
{$_ % 2} {"$_ is an odd number"}
default {"$_ is an even number"}
}
</pre>
 
When executed the following output is generated:
 
<pre>
1 is an odd number
2 is an even number
3 is an odd number
4 is an even number
5 is an odd number
6 is an even number
7 is an odd number
8 is an even number
9 is an odd number
10 is an even number
</pre>
 
Similarly, the elements of an array can be passed through to the switch statement. The following example, the array output from a directory listing is run through the switch statement to identify text and Word documents by checking the file name extension of each file name:
 
<pre>
switch -wildcard (dir)
{
'*.txt' {"$_.name is a text file"}
'*.doc' {"$_.name is a Word document"}
}
</pre>
 
When executed, the output might appear as follows:
 
<pre>
date.txt is a text file
error.txt is a text file
filename.txt is a text file
letter.doc is a Word document
mydata.txt is a text file
mydatafile.txt is a text file
output.txt is a text file
</pre>
 
== Using the continue Statement ==
 
One final statement that has not yet been covered in relation to the Windows PowerShell switch construct is the ''continue'' statement. The ''continue'' statement is particularly when iterating through collections as described above, and serves to return execution to the of the switch statement so that execution can be begin on the next element of the collection, thereby bypassing any other tests that may remain in the statement. In the following example, when an odd number is identified, the switch statement immediately moves on to the next value in the range:
 
<pre>
switch (1..10)
{
{$_ % 2} {"$_ is an odd number"; continue}
default {"$_ is an even number"}
}
</pre>
 
If, on the other hand, a ''break'' statement had been used in place of the ''continue'' in the above example, the switch statement would have exited after the first odd number, instead of continuing to work through the entire range:
 
<pre>
switch (1..10)
{
{$_ % 2} {"$_ is an odd number"; break}
default {"$_ is an even number"}
}
 
1 is an odd number
</pre>

Navigation menu