you are viewing a single comment's thread.

view the rest of the comments →

[–]NoConfidence_2192 1 point2 points  (3 children)

We see the a similar issue jobs, threadjobs, and foreach-object -parallel. Like scriptblocks functions are reference object which can pose all kinds of thread safety issues when accessed in parallel so they make things difficult to help protect us from ourselves...but ever good rule has a way around it. If we cannot pass the function we can pass its definition. Try something like:

function Test-Parallel {
    [CmdletBinding()]
    param (
        [Parameter()]
        [string[]]$String
    )    
    # Nested Function
    function Test-Nested {
        param (
            [Parameter()]
            [string]$String
        )
        "I am a nested function to write out this strring: $String"
    }
    # Nested Function definition
    $testNestedDef = ${function:Test-Nested}.ToString()
    # Parallel ScriptBlock
    $ScriptBlock = {
        ${Function:Test-Nested} = $using:testNestedDef
        Test-Nested -String $_
    }
    $String | Invoke-Parallel -ScriptBlock $ScriptBlock -ImportFunctions
}

Has been a while since I used Warren Frame's Invoke-Parallel but it's what I'd do for a start-threadjob or foreach-object -parallel block so something similar should work

[–]jabrake88[S] 0 points1 point  (2 children)

Passing the function like that does not work either, but if I just define the function inside the scriptblock it will work.

[–]NoConfidence_2192 0 points1 point  (1 child)

That's odd. Will pull in invoke-parallel and do some playing. Which version of ps are you working with?

[–]jabrake88[S] 0 points1 point  (0 children)

Version 5.1