What is ForEach-Object in PowerShell?
PowerShell is a command-line shell and scripting language.
In this shot, we will learn how to use ForEach-Object in PowerShell.
Definition
ForEach-Object is a cmdlet in PowerShell that is used to iterate through a collection of objects.
You can use the $_ operator to access the current object.
Syntax
ForEach-Object {todo operation}
- Use
ForEach-Objecton any output as a collection. - Provide the
operationyou want to perform on each object in between curly braces{}.
Return value
ForEach-Object has no return value and will only perform operations on the provided collection of objects.
Example
In this example, we will try to use ForEach-Object to find the sum of the numbers from 1 to 100.
#declare variable sum$sum = 0#loop through numbers and add it to sum1..100 | ForEach-Object { $sum += $_}$sum
Explanation
In the code snippet above:
- Line 2: Declare and initialize a variable
sum. - Line 5: Use
ForEach-Objectto traverse every number from1to100and add current number$_tosum. The pipe operator|will provide the output of1..100toForEach-Object. - Line 8: Print the sum.
Output
When you run the code snippet above in PowerShell, it will print 5050.