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!
Author Info:
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
More Posts related to Powershell,
- How to upgrade PowerShell on Mac
- How to install AWS CLI 2 on Windows 11 using PowerShell
- How to switch to Powershell on Mac Terminal
- How to connect to Microsoft Exchange Online using PowerShell
- How to Check PowerShell Version? [Windows/Mac/Linux]
- How to Comment out Code in PowerShell Script
- How to Identify installed PowerShell version
- How to install PowerShell on macOS
- Open PowerShell Terminal in Visual Studio Code (VSCode)
- PowerShell ps1 script is not digitally signed, you cannot run this script on the current system
- Update Powershell Using Command Line
- PowerShell 1..10 foreach Example
- PowerShell Fix: Get-Help cannot find the Help files for this cmdlet on this computer
- List of PowerShell Cmdlet Commands for Mac
- Help or Man equivalent in PowerShell
- PowerShell SubString with Examples
- PowerShell: How to Get Folder Size
- PowerShell Traditional For Loop Example
- PowerShell Switch Statement with Examples
- PowerShell Concatenate String Examples
- PowerShell For Each Loop Examples
- PowerShell: Grep Command Alternative - Select-String
- How to delete a file using PowerShell [Windows/macOS]
- Fix: nano is not recognized as an internal or external command - Windows PowerShell
- PowerShell on Mac: The term get-service is not recognized as a name of a cmdlet, function, script file, or executable program
More Posts:
- How to Use Command Prompt on a Mac? - MacOS
- Android xml error Attribute is missing the Android namespace prefix [Solution] - Android
- How to enable Do Not Disturb (DND) mode in Microsoft Teams - Teams
- Check if a file exists or not using Bash Script - Bash
- How to Convert a Java Object into an Optional with Example - Java
- Android Emulator Soft Back button action using Computer keyboard - Android
- Iterate over an Array using Java 8 Stream and foreach - Java
- How to set an emoji as Zsh terminal prompt in macOS - MacOS