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
CustomFunction
– Salem${function:Verb-Noun}
– Jeb${function:Verb-Noun} = $using:funcDef
withinStart-ThreadJob
. I would really appreciate an example. All the examples useForEach-Object -Parallel
; which I can't use and not familiar with. – SalemStart-ThreadJob
to do this. I'm not sure if I need to use-InitializationScript
or what I need to do in order to get the function withinStart-ThreadJob
. I don't have any experience withForEach-Object -Parallel
; and, can't use it anyway. – Salem