ForEach-Object

Perform an operation (execute a block of statements) against each item in a collection of input objects, typically passed through the pipeline.

Syntax
ForEach-Object [-process] ScriptBlock[] [-inputObject psobject]
[-begin scriptblock] [-end scriptblock] [CommonParameters]
key
-process ScriptBlock[]
A block of PowerShell script that is applied to each incoming object.
-inputObject psobject
Accepts an object that the script block specified in the process parameter
will act upon. Enter a variable that contains the objects or type a
command or expression that gets the objects.
-begin scriptblock
A script block to run before processing any input objects.
-end scriptblock
A script block to run after processing all input objects.
CommonParameters:
-Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
-OutBuffer -OutVariable.

For operations in the pipeline, the ForEach alias will take precedence over the ForEach statement.
For operations not in the pipeline the ForEach statement will take precedence.

For the fastest performance: use the ForEach statement (or method) when the collection of objects is small enough that it can be loaded into memory. (eg an array of 20 string values)
Use the ForEach-Object cmdlet when you want to pass only one object at a time through the pipeline, minimising memory usage. (e.g. a directory containing 10,000 files)

Examples

Retrieve the files (and folders) from the C: drive and display the size of each:

In this example, the -Process parameter uses Out-File to create a text file and stores the .message property of each event. The -Begin and -End parameters are used to display the date and time before and after the command has completed.
In this example, the backtick character ` is the PowerShell line continuation character.

“The best way to have a good idea is to have a lot of ideas” ~ Linus Pauling

Related:

ForEach statementForEach (method) - Loop through items in a collectionCompare-Object Compare the properties of objectsGroup-Object - Group the objects that contain the same value for a common propertyMeasure-Object - Measure aspects of object properties and create objects from those valuesNew-Object - Create a new .Net objectSelect-Object - Select objects based on parameters set in the Cmdlet command stringSort-Object - Sort the input objects by property valueTee-Object - Send input objects to two placesWhere-Object - Filter input from the pipeline allowing operation on only certain objects