PowerShell is a command-line shell and scripting language.
In this shot, we will learn how to use ForEach-Object in PowerShell.
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.
ForEach-Object {todo operation}
ForEach-Object on any output as a collection.operation you want to perform on each object in between curly braces {}.ForEach-Object has no return value and will only perform operations on the provided collection of objects.
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
In the code snippet above:
sum.ForEach-Object to traverse every number from 1 to 100 and add current number $_ to sum.
The pipe operator | will provide the output of 1..100 to ForEach-Object.When you run the code snippet above in PowerShell, it will print 5050.