Skip to content

ForEach-Object -Parallel disallows script blocks via $using:, unlike Start-ThreadJob #12378

@mklement0

Description

@mklement0

Start-ThreadJob allows passing a script block by way of a $using: reference, which is a convenient way to make a function from the caller's scope available to the job:

PS> function foo { 'bar' }; Start-ThreadJob { & $using:function:foo } | Receive-Job -Wait -AutoRemoveJob
bar

That is, the foo function's script block ([scriptblock] instance containing the function body) reported by $function:foo (namespace variable notation) was referenced via $using:, allowing it to be called with &.

Unexpectedly, ForEach-Object -Parallel, whose behavior is generally very similar to Start-ThreadJob, explicitly disallows referencing [scriptblock]-typed values from the caller's scope via $using:

Note:

Steps to reproduce

function foo { 'bar' }; ForEach-Object -Parallel { & $using:function:foo } | Should -Be 'bar'

Expected behavior

The test should succeed.

Actual behavior

The test fails, because a statement-terminating error occurs:

A ForEach-Object -Parallel using variable cannot be a script block. 
Passed-in script block variables are not supported with ForEach-Object -Parallel, 
and can result in undefined behavior.

Environment data

PowerShell Core 7.1.0-preview.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-FixedThe issue is fixed.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions