For - PowerShell
Overview
The For
command in PowerShell executes a series of commands repeatedly for a specified number of iterations or until a condition is met. It provides a convenient way to iterate over sequences of objects or values in a loop.
Syntax
For (<LoopVariable> in <Expression>)
{
<Commands to execute>
}
Parameters:
<LoopVariable>
: Name of the variable used to hold the current iteration item.<Expression>
: Expression that defines the sequence of values or objects to loop through.
Options/Flags
None
Examples
Example 1: Loop through a range of numbers from 1 to 10.
For ($i in 1..10)
{
Write-Host "Number: $i"
}
Example 2: Loop through the items in an array.
$myArray = 1, 2, 3, 4, 5
For ($item in $myArray)
{
Write-Host "Item: $item"
}
Example 3: Loop until a condition is met.
$sum = 0
For (; $sum -lt 100;)
{
$sum += Get-Random -Maximum 10
}
Write-Host "Sum reached 100 after $sum iterations"
Common Issues
- Infinite loop: Avoid using a condition that will never be met, leading to an infinite loop.
- Loop variable scope: The loop variable is only visible within the loop block.
- Array index out of bounds: Ensure the array has enough elements to iterate through.
Integration
The For
command can be integrated with other PowerShell commands for more complex tasks:
- Combine with
Where-Object
to filter items based on a condition. - Use
Break
orContinue
to control the loop flow. - Nest multiple
For
loops for more complex iterations.
Related Commands
While
: Executes commands repeatedly while a condition is met.ForEach-Object
: Iterates over each object in a collection.ForEach
: Iterates over each item in a collection and stores results.