Search notes:

PowerShell cmdLet Foreach-Object

Execute a script block in a pipeline

The forEach-object cmdLet can be used to invoke a script block within a pipeline.
1 .. 10 | forEach-object { $_ * $_ }
Github repository about-PowerShell, path: /cmdlets/object/forEach/script-block.ps1

Shorter ways to write forEach-object

forEach-object can be abbreviated with forEach or %.
It should be noted, however, that foreach is also a statement and that the percent sign also acts as the arithmetic modulus operator.

Powershell 7: Parallel execution

With Powershell 7, the objects passed to foreach-object can be processed in parallel by specifying the -parallel parameter:
By default, PowerShell starts up to five threads in parallel:
7,5,2,3,6,4,8,1 | forEach-object -parallel { write-output "Thread $_ started at $(get-date -format 'mm:ss'). PID = $pid, TID = $([System.Threading.Thread]::CurrentThread.ManagedThreadId)"; start-sleep $_; write-output "Thread $_ is stopping" }
The number of maximum concurrent threads can be adjusted with -throttleLimit:
get-random (1..10) -shuffle| forEach-object -parallel { write-output "Thread started at $(get-date -format 'mm:ss'). PID = $pid, TID = $([System.Threading.Thread]::CurrentThread.ManagedThreadId)"; start-sleep $_ } -throttleLimit 8

See also

Powershell command noun: object
map

Index