我有一个复杂的 PowerShell 函数,我想运行另一个线程。
但是,如果我是对的,则无法在脚本块中访问该函数。我想避免复制它旁边的每个相关功能。
有什么方法或方法可以调用脚本块中的函数吗?
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
}
}