Common/Public/New-RunspacePool.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function New-RunspacePool
{
    [OutputType([System.Management.Automation.Runspaces.RunspacePool])]
    [CmdletBinding()]
    param
    (
        [Parameter()]
        [int]
        $ThrottleLimit = 10,

        [Parameter()]
        [System.Threading.ApartmentState]
        $ApartmentState = 'Unknown',

        [Parameter()]
        [System.Management.Automation.PSVariable[]]
        $Variable
    )

    $pool = Get-Variable -Name "ALCommonRunspacePool_$($ThrottleLimit)_$($ApartmentState)" -Scope Global -ErrorAction SilentlyContinue
    $InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()

    foreach ($var in $Variable)
    {
        $sessionVariable = [System.Management.Automation.Runspaces.SessionStateVariableEntry]::new($var.Name, $var.Value, $null)
        $InitialSessionState.Variables.Add($sessionVariable)
    }

    if (-not ($pool))
    {
        Write-Verbose -Message "Creating new runspace pool. Maximum Runspaces: $ThrottleLimit, ApartmentState: $ApartmentState, Variables: $($Variable.Count)"
        $pool = New-Variable -Name "ALCommonRunspacePool_$($ThrottleLimit)_$($ApartmentState)" -Scope Global -Value $([runspacefactory]::CreateRunspacePool($InitialSessionState)) -PassThru
        [void] $($pool.Value.SetMaxRunspaces($ThrottleLimit))
        $pool.Value.ApartmentState = $ApartmentState
    }
        
    $pool.Value
}