The ForEach-Object
cmdlet in PowerShell allows users to iterate through collections such as arrays, collection of objects, or output from other cmdlets, and perform actions on each item individually.
Syntax of ForEach-Object
The syntax of ForEach-Object is as follows.
# Using the pipeline <collection> | ForEach-Object { # Code to execute for each item in the collection } $ Using the ForEach-Object cmdlet directly ForEach-Object -InputObject <Collection> -Process { # Code to execute for each item in the collection }
In this syntax:
- <collection> : represents the collection of items to iterate over.
- –Process : parameter specifies the script block to execute for each item in the collection.
Let’s understand some of the practical ForEach-Object examples in the PowerShell.
How to Use ForEach-Object to Process Output from Cmdlets
Get-Service | ForEach-Object { Write-Host "Service Name: $($_.Name), Status: $($_.Status)" }
In the above PowerShell script, the Get-Service cmdlet outputs a list of services as input to the ForEach-Object
cmdlet. The cmdlet iterates through the collection of service object to print the service name and its status.
How to Iterate Over Arrays using ForEach-Object
$languages = @("Python","PowerShell","Rust","Java") $languages | ForEach-Object { Write-Host "Language: $_" }
In the above PowerShell script, the $languages
variable stores an array of languages. The ForEach-Object
iterates over the collection of items in the array and print the language name on the console.
Conclusion
I hope the above article on how to use ForEach-Object
cmdlet in PowerShell to iterate over an array or collection of items is helpful to you.
Unlike the for loop or foreach loop in PowerShell, the ForEach-Object
operates in a pipeline-friendly manner, making it easier for processing data streams efficiently.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.