0

I have some Powershell functions I want to modify to use multi-threading. They follow a pattern where local functions are defined in the Begin block and consumed in the Process block. When I use Start-Job to multi-thread I can no-longer access the local functions. Is there a way of scoping the local functions to make them available? or is there a better pattern to use for multi-threading advanced functions?

Note: I am using Powershell 5 so can't use foreach parallel.

EXAMPLE

function Test-Jobs {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]
        [string[]]$ComputerName
    )
    Begin {
        
        Write-host "Begin Block"
        
        function DoThing {
            param($ComputerName)
            # may be a long running function
            start-sleep -Seconds 5
            "Did a thing on $ComputerName"
        }
        
        $Jobs = @()
    }
    
    Process {
        Write-host "Process Block"
        
        foreach ($Name in $ComputerName) {
            $Jobs += Start-Job -ScriptBlock {
                DoThing $Using:Name
            }
        }
    }
    
    End {
        Write-host "End Block"
        Wait-Job $jobs
        Receive-Job $jobs
    }
}

OUTPUT

The term 'DoThing' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

  • You can pass the function definition as the scriptblock itself with an argument by providing `-ArgumentList`: `Start-Job -ScriptBlock ${function:DoThing} -ArgumentList $Name`. – Abraham Zinala Jan 11 '23 at 05:00
  • Thanks Abraham, I have not seen that syntax before. However in most of my functions I am building an object from the output of many local functions (not shown in my example) rather than just calling a single function. – Lance Tyler Jan 11 '23 at 05:30
  • Encapsulate your functions and script in a scriptblock, then you can pass it as a scriptblock and each runspace will have defined functions – Doug Maurer Jan 11 '23 at 06:01

0 Answers0