Looping Statements

Often a script needs to loop through items and act on each. PowerShell supports several looping constructs. Examples of the for and foreach constructs are demonstrated here. Others, such as while, also exist but are not covered in this chapter.

image

The preceding example shows a for loop. The method to jump or way to use a step is shown. A jump or step is indicated by the last part of the preceding for loop, where $i+=2 is used. If this example had used $i++ instead, the output would be each number from 0 to 5.

Here’s an example of using foreach:

In this example, within the foreach scriptblock, any number of commands could have ...

Get Microsoft® SQL Server 2008 R2 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.