Loop through a collection (or a set of properties) and perform an operation (execute a block of statements) against each.
Syntax
collection.ForEach(scriptblock_expression)
collection.ForEach(scriptblock_expression, object[] arguments)
collection.ForEach(type convertToType)
collection.ForEach(string propertyName)
collection.ForEach(string propertyName, object[] newValue)
collection.ForEach(string methodName)
collection.ForEach(string methodName, object[] arguments)
Key
collection A collection of objects e.g. filenames, registry keys, servernames
ScriptBlock A block of script to run against each object.
Available in PowerShell 4.0 and later, this method provides faster performance than a ForEach statement.
Examples
Find all the running notepad processes, convert to an @array and kill/stop them:
@(Get-Process –Name notepad).ForEach({ Stop-Process -InputObject $_; })
Loop through a collection of services:
# Get a set of services with names starting R
$services = Get-Service r*
# Display the names and status of each service in the collection
$services.foreach({"$($_.Name)--$($_.status)"})
# as we are passing a single script block argument this can be simplified to:
$services.foreach{"$($_.Name)--$($_.status)"}
“There are two ways of spreading light: to be the candle or the mirror that reflects it” ~ Edith Wharton
Related PowerShell Cmdlets:
$foreach variable - Refers to the enumerator in a foreach loop.
Break statement
Continue statement
ForEach statement.
ForEach-Object - Loop for each object in the pipeline (foreach)
For - Loop through items that match a condition.
IF - Conditionally perform a command.
Switch - Multiple if statements.
While - Loop while a condition is True.
ForEach and Where magic methods by Kirk Munro.