我有一个复杂的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
}
}
我认为在这篇博文中找到的代码可能是您要查找的:
Function ConvertTo-Hex {
Param([int]$Number)
'0x{0:x}' -f $Number
}
#Get body of function
$Definition = Get-Content Function:ConvertTo-Hex -ErrorAction Stop
#Create a sessionstate function entry
$SessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry
-ArgumentList 'ConvertTo-Hex', $Definition
#Create a SessionStateFunction
$InitialSessionState.Commands.Add($SessionStateFunction)
#Create the runspacepool by adding the sessionstate with the custom function
$RunspacePool = [runspacefactory]::CreateRunspacePool(1,5,$InitialSessionState,$Host)
对你的Complex_Function和(我猜(你需要的所有其他函数做类似的事情,它们应该可以被你的运行空间使用。
编辑您在评论中询问如何收集所有功能。路径function:/
可以像目录一样遍历和搜索,因此get-chiditem function:/
获取所有当前定义的函数。
在试验时,似乎在当前脚本中定义的函数或从点源脚本中定义的函数具有空的Source
属性。玩这个。它应该导致你想要的。
$InitialSessionState = [initialsessionstate]::Create()
Get-ChildItem function:/ | Where-Object Source -like "" | ForEach-Object {
$functionDefinition = Get-Content "Function:$($_.Name)"
$sessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry `
-ArgumentList $_.Name, $functionDefinition
$InitialSessionState.Commands.Add($sessionStateFunction)
}