0
0
PowerShellscripting~5 mins

For loop in PowerShell

Choose your learning style9 modes available
Introduction

A for loop helps you repeat a set of actions many times without writing the same code again and again.

When you want to print numbers from 1 to 10.
When you need to process each item in a list one by one.
When you want to repeat a task a fixed number of times, like sending reminders.
When you want to create multiple files with similar names automatically.
Syntax
PowerShell
for (<initialization>; <condition>; <increment>) {
    <commands>
}

Initialization sets the starting point, like a counter.

Condition decides how long the loop runs.

Increment updates the counter each time the loop runs.

Examples
This prints numbers 1 to 5, increasing $i by 1 each time.
PowerShell
for ($i = 1; $i -le 5; $i++) {
    Write-Output $i
}
This counts down from 10 to 1, showing a message each time.
PowerShell
for ($count = 10; $count -gt 0; $count--) {
    Write-Output "Countdown: $count"
}
Sample Program

This script prints a greeting three times, showing the current number.

PowerShell
for ($i = 1; $i -le 3; $i++) {
    Write-Output "Hello number $i"
}
OutputSuccess
Important Notes

Remember to use -le for 'less than or equal' and -gt for 'greater than' in conditions.

PowerShell uses $ before variable names.

Use Write-Output to show text on the screen.

Summary

A for loop repeats actions a set number of times.

It has three parts: start, condition, and step.

Use it to automate repetitive tasks easily.