Skip to content

Provide option in ForEach-Object -parallel to transfer current runspace state #12240

@PaulHigin

Description

@PaulHigin

Summary of the new feature/enhancement

Foreach-Object -parallel currently runs each loop iteration in a runspace initialized to its default state. But users might reasonably expect the runspace state to be the same as the runspace state running the foreach-object cmdlet.

This feature idea is to add a new -UseCurrentState (or something) switch that transfers the current runspace state to each parallel loop iteration runspace.

This would ensure that any modules imported or defined functions are available to each foreach -parallel script.

It is not clear how much of the current runspace state can or should be transferred to the loop runspaces, for example defined global variables are problematic since they are likely not thread safe.

Example:

New-PSDrive -Name ZZ -PSProvider FileSystem -Root c:\temp
1..1 | ForEach-Object -Parallel -UseCurrentState {
    # Should have access to ZZ drive
    dir ZZ:
}

Import-Module -Name c:\temp\Modules\MyModule.psd1
1..1 | ForEach-Object -Parallel -UseCurrentState {
    # Should have access to MyModule functions
    Get-MyInfo -Name Hello
}

This needs to be opt in since it will be a performance hit. Some users will likely be unhappy in the performance degradation for simple scenarios.

Proposed technical implementation details (optional)

Metadata

Metadata

Assignees

Labels

Issue-Enhancementthe issue is more of a feature request than a bugKeepOpenThe bot will ignore these and not auto-closeWG-Cmdlets-Corecmdlets in the Microsoft.PowerShell.Core moduleWG-NeedsReviewNeeds a review by the labeled Working Group

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions