Skip to content

Should $PSScriptRoot be added to foreach-object-Parallel? #15302

Closed

Description

@kasini3000

Should $PSScriptRoot be added to foreach-object-Parallel?

Currently, this automatic variable is not implemented. Use & "${PSScriptRoot}/xxx.ps1 in a child thread, an error will be reported.

Proposed technical implementation details (optional)

 xxx | ForEach-Object  -Parallel {
		${PSScriptRoot} = $using:PSScriptRoot #default add this line
		& "${PSScriptRoot}/xxx.ps1"
}

Paul Higinbotham (@PaulHigin)

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Apr 24, 2021
  2. mklement0 commented on Apr 25, 2021

    @mklement0
    Contributor

    See #12240, which more generally proposes copying the caller's state to the runspaces of the parallel threads on an opt-in basis [update: but $PSScriptRoot would require special handling; see next comment].

  3. SeeminglyScience commented on Apr 26, 2021

    @SeeminglyScience
    Contributor

    Michael Klement (@mklement0) PSScriptRoot would need to be handled on it's own. It's the closest thing PowerShell has to a lexically scoped variable and is overwritten at the start of every new script based command.

    e.g.

    $PSScriptRoot = 'test'
    . { $PSScriptRoot }
    # empty

    -Parallel would need to recreate the scriptblock with something like this:

    var ast = Parser.ParseFile(originalSb.ToString(), originalSb.Ast.Extent.File, out _, out _);
    ast.GetScriptBlock();

    but then the challenge is that the PowerShell API does not make it easy to directly invoke a scriptblock (#15004).

    (I know you already know that last bit, included for context)

  4. PaulHigin commented on Apr 26, 2021

    @PaulHigin
    Contributor

    This can be considered as part of the #12240 work.

  5. added
    Resolution-Duplicate
    and removed
    Needs-Triage
    on Apr 26, 2021
  6. PaulHigin commented on Apr 26, 2021

    @PaulHigin
    Contributor

    Closing and merging as part of #12240.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-EnhancementResolution-Duplicate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions