I am confused with ForEach-Object -Parallel. The following code has $blobs array with more than 2000 blobs. With the regular foreach I can print the names of each blob without a problem. Then using the ForEach-Object -Parallel just after the first foreach, nothing is printed. Why ?
foreach ($blob in $blobs) {
Write-Host $blob.Name
}
# Use parallel processing to process blobs concurrently
$blobs|ForEach-Object -Parallel {
param (
$blob)
Write-Host $blob.Name
} -ThrottleLimit 300
The script block passed to a
ForEach-Objectcmdlet call - whether or not you use-Parallel- receives its (pipeline) input implicitly, via the automatic$_variable (aka$PSItem). (In other words: there's no need for or point in declaring a parameter):By contrast, the
foreachstatement requires a self-chosen iterator variable (such as$blobin your example).foreachis also an alias of theForEach-Objectcmdlet, and it is the syntactic context that decides whetherforeachrefers to the language statement or the cmdlet.Note that the
-ThrottleLimitparameter controls how many threads are allowed at a time. For CPU-bound operations, it doesn't make sense to specify a number higher than the available CPU cores; only for operations that are network-bound, I/O-bound, or wait for events do higher numbers make sense.With respect to the
ForEach-Objectcmdlet, while$_is used both with or without-Parallel, there is an important difference with respect to referencing variables from the caller's scope:With
-Parallel, you need the$using:scope; e.g.: