Section A.8. Loops


A.8. Loops

While looping is a general concept, MSH offers three specific mechanisms for performing iterative tasks: the while loop, the for loop, and the foreach loop.

A.8.1. while Loop

 while (<condition>) { <block> }

The while loop is the simplest of loops and will repeatedly execute a block until a condition no longer holds true. The script block must at some point break the condition or there must be an external expectation that the condition will cease to hold at some point in the future; otherwise, the loop will continue indefinitely.

A.8.2. for Loop

 for (<initialization>; <condition>; <repeat command>) { <block> }

The for loop gives complete control of the start, middle, and end of the loop. Like while, the condition is tested before each run, and the block is executed if a condition holds true. Additionally, a for statement can include an initialization statement that is run once (for example, to set a counter to zero). The repeat command is also optional (but recommended!) and is executed after each run through the block.

A.8.3. foreach Loop

 foreach (<element> in <elements>) { <block> }

The foreach loop is well suited to processes in a collection such as an array or a sequence of objects emitted from a cmdlet. The block is executed once for each object in the elements list. During each invocation, the variable named in the <element> part is populated with the current object.

The foreach language element (described here) is different than the foreach-object cmdlet (which is also aliased as foreach). The foreach-object cmdlet is designed for pipeline use and does not take a (<element> in <elements>) term.




Monad Jumpstart
Monad Jumpstart
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 117

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net