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-Object on any output as a collection.
  • Provide the operation you 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 sum
1..100 | ForEach-Object { $sum += $_}
#print
$sum

Explanation

In the code snippet above:

  • Line 2: Declare and initialize a variable sum.
  • Line 5: Use 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.
  • Line 8: Print the sum.

Output

When you run the code snippet above in PowerShell, it will print 5050.

Free Resources