从其他运行空间会话监视运行空间池的状态

时间:2019-06-25 16:39:19

标签: powershell runspace

我正在使用一个GUI向导,该GUI向导将向用户收集有关其环境的信息,然后在最后一页该工具将调用Runspace池中的28个下标。

我想监视来自另一个运行空间的28个下标的状态,就像我监视GUI运行空间内的状态一样,GUI将冻结。问题是,当我将Async变量添加到SyncHash表并将其传递到另一个运行空间时,状态将全部完成,等于true。

您是否有关于如何从其他运行空间监视运行空间池的状态并在所有28个下标的状态都完成为真之后采取措施的想法。

//The XYZ location of a point:
var x = model.points[i*3];
var y = model.points[i*3+1];
var z = model.points[i*3+2];


//The normal vector direction:
var nx = model.normals[i*3];
var ny = model.normals[i*3+1];
var nz = model.normals[i*3+2];

这是Async Varibale在其他运行空间中的输出,显示为true

            #   Create RunspacePool.
            $RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS + 1, $InitialSessionState, $Host)   #   Create Runspace Pool and add InitialSessionState to it
            $RunspacePool.ApartmentState = "MTA"  # Set Runspace Pool ApartmentState
            $RunspacePool.Open()    #   Open Runspace Pool
            $PSSessions = @()   #   Create an Array to add all PowerShell Session to it to use it when closing the sessions.

            #   Run a ForEach loop on all Subscript files and whith each iteration create a powershell session and call subscript.
            ForEach ($SubScript in $GuiHash.SubscriptFilePath) {
                $PowerShellSession = [powershell]::Create()
                $PowerShellSession.RunspacePool = $RunspacePool
                $AsyncHandle = $PowerShellSession.AddScript($SubScript).BeginInvoke()
                $PSSessions += [PSCustomObject] @{ 
                    Session = $PowerShellSession
                    Invoke = $AsyncHandle
                }
            }

1 个答案:

答案 0 :(得分:0)

在这里,我已经按照您的需求处理了您之前想做的事情:

$PowerShellSession = @()
$Jobs = @()
$Wait = @()

#Loop through online servers for this DC and create a process for each to patch that server (up to 10 at a time)
For($i = 0; $i -lt $GuiHash.SubscriptFilePath.Count; $i++){
    #Create scriptblock from file
    $SB = [scriptblock]::Create((Get-Content $GuiHash.SubscriptFilePath[$i]))
    #Create thread for server
    $PowerShellSession += [powershell]::Create()
    #Add the scripblock to be run in the thread
    $PowerShellSession[$i].AddScript($SB)|Out-Null
    #Assign the runspace pool to this runspace 
    $PowerShellSession[$i].RunspacePool = $RunSpacePool
    #Start the script within its runspace as ASync
    $Jobs += $PowerShellSession[$i].BeginInvoke()
    #Find its wait handle to track the job
    $Wait += $jobs[$i].AsyncWaitHandle
}

#Wait for all jobs to complete
If($Wait){[System.Threading.WaitHandle]::WaitAll($Wait)|Out-Null}

#Collect the jobs
$Results = For($i = 0; $i -lt $Jobs.count;$i++){
    $PowerShellSession[$i].EndInvoke($Jobs[$i])
}

主要区别在于,我捕获了您为数组中每个线程分配的$Asynchandle的{​​{1}}属性,然后告诉PowerShell等待所有等待句柄完成。