PS
Powershell Tutorial Online

Powershell-Foreach

Powershell Foreach and Looping

Every language supports looping. Looping is important part of the programming languages.
PowerShell supports a wide variety of looping features while, foreach, foreach-object, Do-While
Looping allows us to iterate or repeat a block of code.
In Powershell we have Script Block, We will see script Block in deatils at the end of this foreach topic.

While :- The while loop loops through a block of code as long as a specified condition is true.


    while (condition) {
    code block to be executed, you increment values here or do some operations
    }
        
    

    $i=1
    while ($i -le 5) 
    {
    Write-Host "`$i = $i"
    $i= $i +1;
    }
        

Do-While The do/while loop is a just another variant of the while loop. Here only difference is that it always execute at once. Becuase check or validate condition after first block execution. This loop will execute the code block once then it will repeat the loop as long as the condition is true. you can unary operator for incrementaing variable value.


do {
code block to be executed
}
while (condition);


do {
    $i=1
    do {
    Write-Host "`$i = $i"
    $i= $i +1;
    }while ($i -le 5) 
        

Until

For

for($i=0; $i -le 5; $i++)
{
"`$i= $i"
}

Example 4: Another example of for loop, declare initialiser first, this is useful in some scenarios where we get values from some varaible at runtime from another operations.
$i =0  #declare initialiser first
for(; $i -le 5; $i++)
{
"`$i= $i"
}

Example 5 Iterating array or collection

Foreach
Example 6:-