PowerShell Traditional For Loop Example


The traditional for loop is the one you may find in almost all programming languages like C, C++, Java, and so on.

If you are wondering if there is such a for loop in PowerShell, well Yes! Let's take a look at the Syntax and an example.


Syntax:

for (<initialization>; <condition>; <increment>) {

    # Your code within for loop

}

PowerShell For Loop Example:

# For Loop from 1 to 10
for ($i = 1; $i -le 10; $i++) {
    Write-Host "Number: $i"
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10

It is important to note that condition like >=, <= may give you errors!

ParserError: /Users/c2ctechtv/Desktop/hello.ps1:2
Line |
   2 |  for ($i = 0; $i <= 10; $i++) {
     |                  ~
     | The '<' operator is reserved for future use.
OperatorDescriptionPowerShellC / C++Java
Equal toCompare equality-eq==.equals()
Not equal toCompare inequality-ne!=! .equals()
Less thanCompare less than-lt<<
Less than or equal toCompare less than or equal to-le<=<=
Greater thanCompare greater than-gt>>
Greater than or equal toCompare greater than or equal to-ge>=>=
PowerShell For Loop Example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap