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.

PS>for($i=0;$i -lt 5;$i+=2){>> $i>> }>>024PS>

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:

PS C:\book>dir    Directory: Microsoft.PowerShell.Core\FileSystem::C:\bookMode                LastWriteTime     Length ...

Get Microsoft® SQL Server 2012 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.