PowerShell – Looping

There may be a situation when you need to execute a block of law several number of times. In generalstatements are executed succession ally The first statement in a function is executed firstfollowed by the alternate, and so on.

Programming languages give colorful control structures that allow for more complicated prosecution paths.
circle statement allows us to execute a statement or group of statements multiple times and following is the general form of a circle statement in utmost of the programming languages −

 

For loop – Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

> $array = @("item1", "item2", "item3")
> for($i = 0; $i -lt $array.length; $i++){ $array[$i] }
item1
item2
item3

ForEach loop- Enhanced for loop. This is mainly used to traverse collection of elements including arrays.
> $array = @("item1", "item2", "item3")
 
> foreach ($element in $array) { $element }
item1
item2
item3
 
> $array | foreach { $_ }
item1
item2
item3

while loop - Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
> $array = @("item1", "item2", "item3")
$counter = 0;

while($counter -lt $array.length){
   $array[$counter]
   $counter += 1
}
 
item1
item2
item3

do.. while loop- Like a while statement, except that it tests the condition at the end of the loop body.
> $array = @("item1", "item2", "item3")
$counter = 0;

do {
   $array[$counter]
   $counter += 1
} while($counter -lt $array.length)
 
item1
item2
item3 

Leave a Comment