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

-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Powershell,
- PowerShell: How to Check if a Module is Already Installed
- PowerShell: How to Write Output to a File
- PowerShell: Steps to Connect to connect to Exchange Online
- PowerShell Fix: Get-Help cannot find the Help files for this cmdlet on this computer
- PowerShell Traditional For Loop Example
- How to Run PowerShell Script as Administrator (Elevate)
- Update Powershell Using Command Line
- How to delete a file using PowerShell [Windows/macOS]
- PowerShell: Grep Command Alternative - Select-String
- PowerShell Concatenate String Examples
- How to add Sleep to PowerShell Script
- Connect Azure AD (Active Directory) for PowerShell
- How to Open PowerShell on Mac?
- List of PowerShell Function Commands for Mac
- How to Connect to Azure AD Account using PowerShell on Mac
- Download Google Chrome setup exe file using PowerShell
- Set Environment Variable in PowerShell for Mac
- How to switch to Powershell on Mac Terminal
- How to add sleep in Powershell Script
- PowerShell on Mac: The term get-service is not recognized as a name of a cmdlet, function, script file, or executable program
- How to Identify installed PowerShell version
- How to check PowerShell version
- How to install PowerShell on Mac using Brew
- PowerShell Switch Statement with Examples
- PowerShell ISE Alternative for Mac
More Posts:
- 24: Append One String to Another in Python Program - Python-Programs
- Vertically Center Text in a DIV Element - CSS
- Fix: Error: error:0308010C:digital envelope routines::unsupported NodeJs/Vue/React - JavaScript
- SQLite Error: unknown command or invalid arguments: open. Enter .help for help - Android
- Get HTTP Request Response Headers Safari Browser - MacOS
- iOS 14 Airpods Connected message everytime when the iPhone is unlocked - Apple
- Ubuntu zsh: command not found: nano - zsh
- Program 12: Calculate Area and Circumference of Circle - 1000+ Python Programs - Python-Programs