0
0
PowerShellscripting~5 mins

ForEach loop in PowerShell

Choose your learning style9 modes available
Introduction
A ForEach loop helps you repeat a set of actions for each item in a list or collection. It saves time by automating repetitive tasks.
You want to print each name in a list of friends.
You need to check every file in a folder.
You want to send an email to each person in a contact list.
You want to add a prefix to every item in a list.
You want to calculate the total of numbers in a list.
Syntax
PowerShell
foreach ($item in $collection) {
    # commands to run for each $item
}
The variable $item holds the current element from the collection during each loop.
The collection can be an array, list, or any group of items.
Examples
Prints numbers from 1 to 5, one per line.
PowerShell
foreach ($number in 1..5) {
    Write-Output $number
}
Greets each name in the list.
PowerShell
foreach ($name in @('Anna', 'Bob', 'Cara')) {
    Write-Output "Hello, $name!"
}
Lists the names of all files in the current folder.
PowerShell
foreach ($file in Get-ChildItem -Path .) {
    Write-Output $file.Name
}
Sample Program
This script goes through each fruit in the list and prints a sentence saying you like that fruit.
PowerShell
foreach ($fruit in @('Apple', 'Banana', 'Cherry')) {
    Write-Output "I like $fruit"
}
OutputSuccess
Important Notes
You can use any variable name instead of $item; just keep it consistent inside the loop.
Make sure the collection is not empty, or the loop will not run.
Use curly braces { } to group the commands that run for each item.
Summary
ForEach loops repeat actions for every item in a list.
They help automate tasks that involve multiple items.
Use foreach ($var in $collection) { } syntax in PowerShell.