PowerShell for Windows Admins

Jun 24 2011   12:41PM GMT

PowerShell Basics: Loops

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: