Monthly Archive

PowerShell Basics: Loops

A loop is used to repeat one or more commands a certain number of times or while a condition is true.  There are a number of ways of generating a loop in PowerShell. These examples show the basic structure of each loop type.

1..10 | foreach-object {$_}            
1..10 | foreach {$_}            
            
$xs = 1..10            
foreach ($x in $xs){$x}            
            
for ($i=0; $i -le $($xs.length-1); $i++){$xs[$i]}            
            
$i = 0            
while ($i -le $($xs.length-1)){$xs[$i]; $i++}            
            
$i = 0            
do {$xs[$i]; $i++} while ($i -le $($xs.length-1))            
            
$i = 0            
do {$xs[$i]; $i++} until ($i -gt $($xs.length-1))

Foreach can be an alias of foreach-object is its on the pipeline or a command to iterate through a collection of objects if its a standalone key word

The do loop has two structures depending on how you want to test the terminating condition.

Experiment with these structures so you understand the implications.

I tend to try and use them in the following order of preference:

  • foreach-object
  • foreach (keyword)
  • for / while
  • do

Leave a Reply