Repeat Operations with Loops
1. Problem
You want to execute the same block of code more than once.
2. Solution
Use one of PowerShell’s looping statements (for, foreach, while, and do), or PowerShell’s Foreach-Object cmdlet to run a command or script block more than once. For a detailed description of these looping statements, see “Looping Statements” in . For example:
Code View: Scroll / Show All
       for loop
               for($counter = 1; $counter -le 10; $counter++)
               {
                  "Loop number $counter"
               }
       foreach loop
               foreach($file in dir)
               {
                  "File length: " + $file.Length
               }
       Foreach-Object cmdlet
              Get-ChildItem | Foreach-Object { "File length: " + $_.Length }
Â
       while loop
               $response = ""
               while($response -ne "QUIT")
               {
                  $response = Read-Host "Type something"
               }
       do..while loop
               $response = ""
               do
               {
                  $response = Read-Host "Type something"
               } while($response -ne "QUIT")                                    Â
3. Discussion
Although any of the looping statements can be written to be functionally equivalent to any of the others, each lends itself to certain problems.
You usually use a for loop when you need to perform an operation an exact number of times. Because using it this way is so common, it is often called a counted for loop.
You usually use a foreach loop when you have a collection of objects and want to visit each item in that collection. If you do not yet have that entire collection in memory (as in the dir collection from the foreach example above), the Foreach-Object cmdlet is usually a more efficient alternative.
Unlike the foreach loop, the Foreach-Object cmdlet allows you to process each element in the collection as PowerShell generates it. This is an important distinction; asking PowerShell to collect the entire output of a large command (such as Get-Content hugefile.txt) in a foreach loop can easily drag down your system.
A handy shortcut to repeat an operation on the command line is:
       PS >1..10 | foreach { "Working" }
       Working
       Working
       Working
       Working
       Working
       Working
       Working
       Working
       Working
       Working
The while and do..while loops are similar, in that they continue to execute the loop as long as its condition evaluates to true. A while loop checks for this before ever running your script block, while a do..while loop checks the condition after running your script block.
Tags: cmd, cmdlet, cmdlets, kernel, longhorn, loop, loops, operation, power shell, repeat script, script, shell, vista, windows 2008
