Common/Public/Start-RunspaceJob.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
40
41
42
43
44
function Start-RunspaceJob
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        [System.Management.Automation.ScriptBlock]
        $ScriptBlock,

        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.RunspacePool]
        $RunspacePool,

        [Parameter()]
        [Object[]]
        $Argument
    )

    if ($RunspacePool.RunspacePoolStateInfo.State -eq 'Closed')
    {
        Write-Error -Message "Runspace pool $($RunspacePool.InstanceId) is already closed. Cannot queue job."
        return
    }

    if ($RunspacePool.RunspacePoolStateInfo.State -ne 'Opened')
    {
        $RunspacePool.Open()
    }

    $shell = [powershell]::Create()
    $shell.RunspacePool = $RunspacePool
    [void] $($shell.AddScript($ScriptBlock, $true))

    foreach ($arg in $Argument)
    {
        [void] $($shell.AddArgument($arg))
    }

    [PSCustomObject]@{
        Shell  = $shell
        Handle = $shell.BeginInvoke()
    }
}