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.