I have a complex PowerShell function which I would like to run another threads.
However, If I'm right, the function cannot be accessed in the scriptblock. I want to avoid to copy every related function next to it.
Is there any way or method to call the function in the scriptblock?
function Function1 {
Param()
Process {
$param1 = "something"
$pool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS + 1)
$pool.ApartmentState = "MTA"
$pool.Open()
$runspaces = @()
$scriptblock = {
Param (
[Object] [Parameter(Mandatory = $true)] $param1
)
Complex_Function -param1 $param1
}
1..10 | ForEach-Object {
$runspace = [PowerShell]::Create()
$null = $runspace.AddScript($scriptblock)
$null = $runspace.AddArgument($param1)
$runspace.RunspacePool = $pool
$runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() }
}
while ($runspaces.Status -ne $null) {
$completed = $runspaces | Where-Object { $_.Status.IsCompleted -eq $true }
foreach ($runspace in $completed) {
$runspace.Pipe.EndInvoke($runspace.Status)
$runspace.Status = $null
}
}
$pool.Close()
$pool.Dispose()
}
}
function Complex_Function {
Param(
[Object] [Parameter(Mandatory = $true)] $param1
)
Process {
#several function calls
}
}