How to loop through a PowerShell array

Now, we will see how to loop through an array in PowerShell using for loop.

For ($i=0; $i -le 5; $i++) {
    "Number is: "+$i
    }

The above PowerShell array will print the numbers starting from 0 to 5.



In the case of a for loop, you will set up the value of a variable and then there will be a condition on which the loop will be terminated.


Below is the another example of a string array, below is how we can loop through a string array using for loop in PowerShell.

$employees = @("Bijay","Bhawana","Padmini","Lakshmi")
For ($i=0; $i -lt $employees.Length; $i++) {
    $employees[$i]
    }

The above array will print all the names from the array like below:




PowerShell array foreach loop

Now, we will see how to loop through an array using foreach loop in PowerShell.


Syntax:

ForEach (item In collection) {code block}

Here item represents the current item, collection is the item collection.


Example:

$numbers=1,2,3,4,5
foreach ($num in $numbers) {
  $num;
 }

You can see the output like below:




Now, we will see how to loop array of strings using PowerShell using foreach loop.

$employees = @("Bijay","Bhawana","Padmini","Lakshmi")
foreach ($emp in $employees) {
  $emp;
 }

You can see the output look like below:




PowerShell While Loop

Now, we will see how to use while loop in PowerShell arrary.


Syntax:

while (condition) {code block}

Example:

$i=1
While ($i -le 5)
    {
    $i
    $i++
    }

You can see the output like below:




PowerShell array do-while loop

Now, we will see how to use do-while loop to loop through a PowerShell array.

$i=1
Do {
    $i
    $i++
    }
While ($i -le 5)

You can see the output like below:


powershell loop array do-while loop


Loop through PowerShell array using Do-Until loop

Now, we will see how to loop through a PowerShell array using the do-until loop.

$i=1
Do {
    $i
    $i++
    }
Until ($i -gt 5)

You can see the output looks like below:



In this tutorial we learned how to loop through an array using for look, foreach loop, while loop, do while loop, do until loop in PowerShell.


Source: SPGuide


The Tech Platform

www.thetechplatform.com

0 comments