How to Use foreach in PowerShell: Syntax and Examples
In PowerShell, use the
foreach keyword to loop through each item in a collection or array. The syntax is foreach ($item in $collection) { ... }, where you run commands for each $item. This lets you automate repetitive tasks easily.Syntax
The foreach loop in PowerShell iterates over each element in a collection. The basic syntax is:
$item: A variable representing the current element.$collection: The array or collection to loop through.- Curly braces
{ }: Enclose the commands to run for each item.
powershell
foreach ($item in $collection) {
# Commands using $item
}Example
This example shows how to loop through an array of fruit names and print each one.
powershell
$fruits = @('Apple', 'Banana', 'Cherry') foreach ($fruit in $fruits) { Write-Output "I like $fruit" }
Output
I like Apple
I like Banana
I like Cherry
Common Pitfalls
Common mistakes include:
- Forgetting the
inkeyword, which causes syntax errors. - Using the wrong variable name inside the loop.
- Trying to modify the collection while looping over it.
Here is a wrong and right example:
powershell
# Wrong: missing 'in'
# foreach ($item $collection) {
# Write-Output $item
# }
# Right:
foreach ($item in $collection) {
Write-Output $item
}Quick Reference
Tips for using foreach in PowerShell:
- Use
foreachto process each item in arrays, lists, or output from commands. - Use
Write-Outputor other commands inside the loop to act on each item. - Remember
foreachis different fromForEach-Object, which is used in pipelines.
Key Takeaways
Use
foreach ($item in $collection) { } to loop through each element in PowerShell.Always include the
in keyword to avoid syntax errors.Inside the loop, use the loop variable to access the current item.
Do not modify the collection you are looping over to prevent unexpected behavior.
foreach is ideal for running commands on each item in a list or array.