Search code examples
powershellstart-job

Reuse 2 functions in Start-ThreadJob


Assuming Get-Foo and Get-Foo2 and Deploy-Jobs are 3 functions that are part of a very large module. I would like to use Get-Foo and Get-Foo2 in Deploy-Jobs's Start-ThreadJob (below) without reloading the entire module each time.

Is an working example available for how to do this?

function Deploy-Jobs {

    foreach ($Device in $Devices) {

        Start-ThreadJob -Name $Device -ThrottleLimit 50 -InitializationScript $initScript -ScriptBlock {
            param($Device)

            Get-Foo | Get-Foo2 -List
        
        } -ArgumentList $Device | out-null
    }
}

Solution

  • The method you can use to pass the function's definition to a different scope is the same for Invoke-Command (when PSRemoting), Start-Job, Start-ThreadJob and ForeEach-Object -Parallel. Since you want to invoke 2 different functions in your job's script block, I don't think -InitializationScript is an option, and even if it is, it might make the code even more complicated than it should be.

    You can use this as an example of how you can store 2 function definitions in an array ($def), which is then passed to the scope of each TreadJob, this array is then used to define each function in said scope to be later used by each Job.

    function Say-Hello {
        "Hello world!"
    }
    
    function From-ThreadJob {
        param($i)
        "From ThreadJob # $i"
    }
    
    $def = @(
        ${function:Say-Hello}.ToString()
        ${function:From-ThreadJob}.ToString()
    )
    
    function Run-Jobs {
        param($numerOfJobs, $functionDefinitions)
    
        $jobs = foreach($i in 1..$numerOfJobs) {
            Start-ThreadJob -ScriptBlock {
                # bring the functions definition to this scope
                $helloFunc, $threadJobFunc = $using:functionDefinitions
                # define them in this scope
                ${function:Say-Hello} = $helloFunc
                ${function:From-ThreadJob} = $threadJobFunc
                # sleep random seconds
                Start-Sleep (Get-Random -Maximum 10)
                # combine the output from both functions
                (Say-Hello) + (From-ThreadJob -i $using:i)
            }
        }
    
        Receive-Job $jobs -AutoRemoveJob -Wait
    }
    
    Run-Jobs -numerOfJobs 10 -functionDefinitions $def