While


The While statement is similar to the For statement. This logical construct also executes a block of code as long as some condition is true: while (<condition>){<command_block>}

However, the syntax is a little more direct. Here's essentially the same loop as we used before, only it has been rewritten to use the While operator:

 PS C:\> $i=1 PS C:\> while ($i -le 10) >> { >>  write-host "loop #"$i >>  $i++ >> } >> loop # 1 loop # 2 loop # 3 loop # 4 loop # 5 loop # 6 loop # 7 loop # 8 loop # 9 loop # 10 PS C:\> 

In this example we've broken the While operation into separate lines to make it easier to follow. Although this could have been written as one line:

 while ($i -le 10){write-host "loop #"$i;$i++} 

Do While

A variation on While is Do While. In the While operation, the condition is checked at the beginning of the statement. In the Do While operation, it is checked at the end:

 PS C:\> $i=0 PS C:\> do { >> $i++ >> write-host "`$i="$i >> } >> while ($i -le 5) >> $i= 1 $i= 2 $i= 3 $i= 4 $i= 5 $i= 6 PS C:\> 

In this example you can see what happens when you check at the end. The loop essentially says increase $i by one and display the current value as long as $ is less than or equal to 5.

However, notice that we end up with a 6th pass. This occurs because when $i=5, the while condition is still true so the loop repeats, including running the increment and display code. But now when the while clause is evaluated it is FALSE, which causes the loop to end. This is not necessarily a bad thing. This type of loop will always run at least once until the While clause is evaluated. It will continue looping for as long as the condition is TRUE.

Do Until

A similar loop is Do Until. Like Do While, the expression is evaluated at the bottom of the loop. This construct will keep looping until the expression is TRUE:

 PS C:\> do { >> $i++ >> write-host "`$i="$i >> } >> until ($i -ge 5) >> $i= 1 $i= 2 $i= 3 $i= 4 $i= 5 PS C:\> 

This is almost the same code block that we used with Do While. However, the conditional expression uses -ge instead of -le. The advantage of using Do Until is that the loop ends when we expect because when one $i equals 5, the loop exits. Again, we want to stress that there is nothing wrong with using Do loops instead of While. It all depends on what you are trying to achieve.



Windows PowerShell. TFM
Internet Forensics
ISBN: 982131445
EAN: 2147483647
Year: 2004
Pages: 289

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net