If you want to iterate over a collection of items in PowerShell, you can make use of the ForEach-Object cmdlet.
Syntax:
ForEach-Object
[-InputObject ]
[-Begin ]
[-Process]
[-End ]
[-RemainingScripts ]
[-WhatIf]
[-Confirm]
[]
Examples: Iterate over an Array of Strings
$cityNames = @("New York", "Los Angeles", "Chicago", "San Francisco")
# Loop through the array using ForEach-Object
$cityNames | ForEach-Object {
Write-Host "$_"
}
Output:
New York
Los Angeles
Chicago
San Francisco
Examples: Iterate over an Array of Numbers
$numbers = @(10, 20, 30, 40, 50)
$numbers | ForEach-Object {
Write-Host "$_"
}
Output:
10
20
30
40
50

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!