In the previous tutorial, we discussed the PowerShell for loop. Now, I will show you some more advanced examples, known as PowerShell for loop with index and range examples.
In this tutorial, I will show you some practical examples of using for loops with indexes and ranges in PowerShell, along with various techniques I’ve learned over the years.
Basic For Loop Syntax in PowerShell
The for loop in PowerShell follows a similar structure to many other programming languages:
for (initialization; condition; increment) {
# Code to execute
}Let’s break this down:
- Initialization: Sets up your counter variable (typically $i)
- Condition: Evaluates before each loop iteration
- Increment: Executes after each loop iteration
Here’s a simple example that counts from 1 to 5:
for ($i = 1; $i -le 5; $i++) {
Write-Output "Current count: $i"
}Check out PowerShell ForEach
Iterate Through Arrays Using Index
One of the most common uses of for loops with indexes is to iterate through arrays. This gives you more control than foreach loops because you have access to the position of each element.
$states = "California", "Texas", "Florida", "New York", "Pennsylvania"
for ($i = 0; $i -lt $states.Count; $i++) {
Write-Output "State #$($i+1): $($states[$i])"
}The output shows each state with its position:
State #1: California
State #2: Texas
State #3: Florida
State #4: New York
State #5: PennsylvaniaHere is the exact output in the screenshot below:

Check out Concatenate Strings Inside Loops in PowerShell
Working with Ranges in PowerShell
PowerShell makes it easy to create ranges using the range operator (..). This is particularly useful when you need to iterate through a specific range of numbers.
# Create a range from 1 to 10
$range = 1..10
for ($i = 0; $i -lt $range.Count; $i++) {
Write-Output "The square of $($range[$i]) is $([Math]::Pow($range[$i], 2))"
}Here is the exact output in the screenshot below:

Process Array Elements in Reverse Order
Sometimes you need to process elements in reverse order. Here’s how to do it with a for loop:
$months = "January", "February", "March", "April", "May"
for ($i = $months.Count - 1; $i -ge 0; $i--) {
Write-Output "Month in reverse order: $($months[$i])"
}Step Through Arrays with Custom Increments
You’re not limited to incrementing by 1. Here’s an example where we step through an array by 2:
$numbers = 1..20
for ($i = 0; $i -lt $numbers.Count; $i += 2) {
Write-Output "Every other number: $($numbers[$i])"
}Read Multiple Conditions in Do-While Loop in PowerShell
Using For Loops with Ranges for Data Processing
Let’s look at a more practical example. Imagine we have sales data for different quarters and want to calculate quarterly averages:
$quarterlySales = @(
@(15000, 17500, 14200), # Q1 sales (Jan, Feb, Mar)
@(18200, 19500, 17800), # Q2 sales (Apr, May, Jun)
@(12500, 13800, 15200), # Q3 sales (Jul, Aug, Sep)
@(21500, 22800, 24700) # Q4 sales (Oct, Nov, Dec)
)
for ($q = 0; $q -lt $quarterlySales.Count; $q++) {
$quarterData = $quarterlySales[$q]
$total = 0
for ($m = 0; $m -lt $quarterData.Count; $m++) {
$total += $quarterData[$m]
}
$average = $total / $quarterData.Count
Write-Output "Quarter $($q+1) average sales: `$$([Math]::Round($average, 2))"
}Working with String Characters Using Indexes
You can also use for loops to process individual characters in strings:
$sentence = "PowerShell is awesome!"
for ($i = 0; $i -lt $sentence.Length; $i++) {
if ($sentence[$i] -match '[aeiou]') {
Write-Output "Vowel found at position $i: $($sentence[$i])"
}
}Using For Loops with Dynamic Ranges
Sometimes, you need to work with ranges that are determined at runtime:
function Process-DateRange {
param (
[DateTime]$startDate,
[DateTime]$endDate
)
$days = ($endDate - $startDate).Days
for ($i = 0; $i -le $days; $i++) {
$currentDate = $startDate.AddDays($i)
Write-Output "Processing data for: $($currentDate.ToString('MM/dd/yyyy'))"
}
}
# Example: Process the first week of May 2023
Process-DateRange -startDate "05/01/2023" -endDate "05/07/2023"Check out While Loop in PowerShell
Create a Loop with Index for CSV Processing
Here’s a practical example that processes a CSV file using indexes:
$csvData = Import-Csv -Path "C:\Data\sales_records.csv"
for ($i = 0; $i -lt $csvData.Count; $i++) {
$record = $csvData[$i]
# Skip processing for certain records based on index
if ($i % 10 -eq 0) {
Write-Output "Milestone record $i: $($record.ProductName), Sales: $($record.Amount)"
}
# Example of updating records based on index
if ($i -lt 5) {
$record.Category = "Premium-" + $record.Category
}
}Using For Loop with Break and Continue
For loops also support flow control with break and continue:
$temperatures = 68, 72, 65, 83, 90, 92, 87, 71, 78, 74
for ($i = 0; $i -lt $temperatures.Count; $i++) {
# Skip temperatures below 70
if ($temperatures[$i] -lt 70) {
Write-Output "Skipping day $($i+1): $($temperatures[$i])°F (too cool)"
continue
}
# Stop processing if we find a temperature above 90
if ($temperatures[$i] -gt 90) {
Write-Output "Alert on day $($i+1): $($temperatures[$i])°F (too hot)"
break
}
Write-Output "Day $($i+1): $($temperatures[$i])°F (comfortable)"
}Working with Multiple Arrays Simultaneously
You can use indexes to work with multiple arrays in parallel:
$products = "Laptop", "Phone", "Tablet", "Monitor", "Keyboard"
$prices = 1200, 800, 350, 250, 80
$inventory = 15, 28, 32, 10, 45
for ($i = 0; $i -lt $products.Count; $i++) {
$totalValue = $prices[$i] * $inventory[$i]
Write-Output "Product: $($products[$i]) | Price: $($prices[$i]) | Inventory: $($inventory[$i]) | Total Value: $totalValue"
}PowerShell for loops with indexes and ranges are beneficial. Whether you’re processing arrays, iterating through specific ranges, or need precise control over loop execution, the for loop can be used.
I hope you now learn everything about PowerShell for loops with indexes and ranges examples. If you have any questions or want to share how you use for loops in your projects, I’d love to hear from you in the comments below!
You may also like:
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.