Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

powershell
communitycreator

What is ForEach-Object in PowerShell?

Gutha Vamsi Krishna

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

powershell
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring