Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Indexing fails on $using: statements #17

Closed
santisq opened this issue Jan 25, 2024 · 0 comments · Fixed by #18
Closed

Indexing fails on $using: statements #17

santisq opened this issue Jan 25, 2024 · 0 comments · Fixed by #18
Assignees
Labels
bug Something isn't working

Comments

@santisq
Copy link
Owner

santisq commented Jan 25, 2024

$a = 0..10
1 | Invoke-Parallel { $using:a[1] }

Fails with:

Exception calling "GetValue" with "1" argument(s): "Cannot process argument because the value of argument "path" is not valid. Change the value of the "path" argument and run the operation again."

To handle indexing on using statements the https://github.com/santisq/PSParallelPipeline/blob/main/Module/public/Invoke-Parallel.ps1#L67-L85 should be changed to:

using namespace System.Management.Automation.Language
using namespace System.Text

$usingparams = @{}
$var = @(1, 2, 3); $vAr2 = @{ foo = 'bar' }
$ScriptBlock = { $using:var[0]; $using:var; $using:VAR2['FOO']; $using:var[2] }

foreach ($usingstatement in $ScriptBlock.Ast.FindAll({ $args[0] -is [UsingExpressionAst] }, $true)) {
    $variableAst = [UsingExpressionAst]::ExtractUsingVariable($usingstatement)
    $varPath = $variableAst.VariablePath.UserPath
    $varText = $usingstatement.ToString()

    if ($usingstatement.SubExpression -is [VariableExpressionAst]) {
        $varText = $varText.ToLowerInvariant()
    }

    $key = [Convert]::ToBase64String([Encoding]::Unicode.GetBytes($varText))

    if ($usingParams.ContainsKey($key)) {
        continue
    }

    $value = $ExecutionContext.SessionState.PSVariable.GetValue($varPath)

    if ($usingstatement.SubExpression -is [IndexExpressionAst]) {
        $idx = $usingstatement.SubExpression.Index.SafeGetValue()
        $value = $value[$idx]
    }

    $usingParams.Add($key, $value)
}

[powershell]::Create().
    AddScript($ScriptBlock).
    AddParameters(@{ '--%' = $usingparams }).
    Invoke()

With $PSCmdlet instead of $ExecutionContext.

@santisq santisq self-assigned this Jan 25, 2024
@santisq santisq added the bug Something isn't working label Jan 25, 2024
@santisq santisq linked a pull request Jan 25, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant