Skip to content

ForEach-Object -Parallel does not accept a scriptblock variable containing a $using #21332

@DarkLite1

Description

@DarkLite1

Prerequisites

Steps to reproduce

Test.ps1

Param (
    [Parameter(Mandatory)]
    [String]$FruitName,
    [Parameter(Mandatory)]
    [Int]$MaxConcurrentJobs
)

$scriptBlock = {
    #region Declare variables for parallel execution
    if (-not $MaxConcurrentJobs) {
        $FruitName = $using:FruitName
    }
    #endregion

    $FruitName
}

#region Run code serial or parallel
$foreachParams = if ($MaxConcurrentJobs -eq 1) {
    @{
        Process = $scriptBlock
    }
}
else {
    @{
        Parallel      = $scriptBlock
        ThrottleLimit = $MaxConcurrentJobs
    }
}
#endregion

0..2 | ForEach-Object @foreachParams

Run the code

$params = @{
    FilePath          = '.\Test.ps1'
    ArgumentList      = @( 'kiwi', 2 )
    ComputerName      = 'PC1'
    ConfigurationName = 'PowerShell.7'
    ErrorAction       = 'Stop'
}
Invoke-Command @params -Verbose

$argumentList = $params.ArgumentList
& $params.FilePath @argumentList

Probably a regression, see PR-16564

Expected behavior

'kiwi'
'kiwi'
'kiwi'

Actual behavior

> The value of the using variable '$using:FruitName' cannot be retrieved because it has not been set in the local session.

Error details

Exception             : 
    Type        : System.Management.Automation.RuntimeException
    ErrorRecord : 
        Exception             : 
            Type    : System.Management.Automation.ParentContainsErrorRecordException
            Message : The value of the using variable '$using:FruitName' cannot be retrieved because it has not been set in the local session.
            HResult : -2146233087
        CategoryInfo          : InvalidOperation: (:) [], ParentContainsErrorRecordException
        FullyQualifiedErrorId : UsingVariableIsUndefined
        InvocationInfo        : 
            ScriptLineNumber : 11
            OffsetInLine     : 22
            HistoryId        : -1
            ScriptName       : T:\Test.ps1
            Line             : $FruitName = $using:FruitName

            Statement        : $using:FruitName
            PositionMessage  : At T:\Test.ps1:11 char:22
                               +         $FruitName = $using:FruitName
                               +                      ~~~~~~~~~~~~~~~~
            CommandOrigin    : Internal
        ScriptStackTrace      : at <ScriptBlock>, <No file>: line 13
    TargetSite  : 
        Name          : GetUsingVariableValues
        DeclaringType : Microsoft.PowerShell.Commands.PSExecutionCmdlet
        MemberType    : Method
        Module        : System.Management.Automation.dll
    Message     : The value of the using variable '$using:FruitName' cannot be retrieved because it has not been set in the local session.
    Source      : System.Management.Automation
    HResult     : -2146233087
    StackTrace  : 
   at Microsoft.PowerShell.Commands.PSExecutionCmdlet.GetUsingVariableValues(List`1 paramUsingVars)
   at Microsoft.PowerShell.Commands.PSExecutionCmdlet.GetConvertedScript(List`1& newParameterNames, List`1& newParameterValues)
   at Microsoft.PowerShell.Commands.PSExecutionCmdlet.GetPowerShellForPSv2()
   at Microsoft.PowerShell.Commands.PSExecutionCmdlet.CreatePipeline(RemoteRunspace remoteRunspace)
   at Microsoft.PowerShell.Commands.PSExecutionCmdlet.CreateHelpersForSpecifiedComputerNames()
   at Microsoft.PowerShell.Commands.PSExecutionCmdlet.BeginProcessing()
   at Microsoft.PowerShell.Commands.InvokeCommandCommand.BeginProcessing()
   at System.Management.Automation.Cmdlet.DoBeginProcessing()
   at System.Management.Automation.CommandProcessorBase.DoBegin()
CategoryInfo          : InvalidOperation: (:) [Invoke-Command], RuntimeException
FullyQualifiedErrorId : UsingVariableIsUndefined,Microsoft.PowerShell.Commands.InvokeCommandCommand
InvocationInfo        : 
    MyCommand        : Invoke-Command
    ScriptLineNumber : 13
    OffsetInLine     : 1
    HistoryId        : 59
    Line             : Invoke-Command @params -Verbose
    Statement        : Invoke-Command @params -Verbose
    PositionMessage  : At line:13 char:1
                       + Invoke-Command @params -Verbose
                       + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    InvocationName   : Invoke-Command
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 13

Environment data

Name                           Value
----                           -----
PSVersion                      7.4.1
PSEdition                      Core
GitCommitId                    7.4.1
OS                             Microsoft Windows 10.0.20348
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Metadata

Metadata

Labels

Needs-TriageThe issue is new and needs to be triaged by a work group.WG-Enginecore PowerShell engine, interpreter, and runtimeWG-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