Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
992 views
in PowerShell by 66 69 85

How to work with loops in PowerShell, I need to use FOR loop in PowerShell Script and I think it has a different syntax from programming languages. 

The following example or C# programming language.

for (int i = 0; i < 5; i++) 
{
  Console.WriteLine(i);
}
int i = 0;
while (i < 5) 
{
  Console.WriteLine(i);
  i++;
}

How can I do the same FOR or WHILE looping concept in PowerShell?


1 Answer

1 like 0 dislike
by 66 69 85
 
Best answer

FOR Loop in PowerShell

In the beginning, we need to understand the comparison operators

-eq  #equal =
-ne  #not equal !=
-gt  #greater than >
-lt  #less than <
-le  #less than or equal <=
-ge  #grater than or equal >=

1) How to use For Loop in PowerShell?

for($i = 0; $i -lt 5; $i++){
    $i
}

Output:

0
1
2
3
4

2) How to use While Loop in PowerShell?

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

Output:

1
2
3
4
5

3) How to use Foreach Loop in PowerShell?

$numbers = 22,5,10,8,12,9,80

foreach($number in $numbers){
    if($number -le 10){
         $number
    }
}

Output:

5
10
8
9
If you don’t ask, the answer is always NO!
...