我正在创建一个运行空间池,该池将有多个运行空间在不同的时间开始停止。阵列列表中的运行空间的Register-ObjectEvent
为了跟踪这个我所有的运行空间进入一个集合。
我正在尝试为每个对象注册一个对象事件,以便我可以从GUI中向用户返回运行空间的信息。
在那里我有问题的部分是在这里:
$Global:RunspaceCollection
$Global:x = [Hashtable]::Synchronized(@{})
$RunspaceCollection = @()
[Collections.Arraylist]$Results = @()
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1,5)
$RunspacePool.Open()
$action = {
Foreach($Runspace in $Global:RunspaceCollection.ToArray()) {
If ($Runspace.runspace.iscompleted){
$results.add($runspace.powershell.endinvoke($Runspace.runspace))
$runspace.powershell.dispose()
$runspacecollection.remove($Runspace)
Write-Host "I AM WORKING"
test-return
}
}
Function Start-PasswordReset($username) {
$scriptblock = {
Param($userame)
start-sleep -Seconds 10
$Result = "I have reset" + $username
$result
}
$Powershell = [PowerShell]::Create().AddScript($ScriptBlock).AddArgument($username)
$Powershell.RunspacePool = $RunspacePool
[Collections.Arraylist]$Global:RunspaceCollection += New-Object -TypeName PSObject -Property @{
Runspace = $PowerShell.BeginInvoke()
PowerShell = $PowerShell
}
Register-ObjectEvent -InputObject $runspacecollection[0].Runspace -EventName statechanged -Action $Action
}
}
的代码在寄存器objectevent线失败,目前我已经硬编码0进行测试,但是这将是目前的运行空间数在最终版本中。我不知道我是否犯了一个小错误,或者对这个工作原理缺乏了解,我愿意接受这两种可能性!
目前尚不清楚你试图实际完成什么。您发布的代码无法正常工作,它无法将New-Object添加到数组列表中,但这不能是完整的代码吗?注册对象事件需要一个对象发出的事件,所以在你的情况下,PSObject.Runspace应该有一个StateChanged事件。请提供更完整的代码清单或更详细的说明,说明您正在努力完成的任务。 –
不,它不是完整的代码,我将在回到Tommorow时发布它。本质上,我期待存储在集合中的Runspace对象有一个statechanged事件,但是当我检查get-member时,它缺少。 – Lister
@BenRichards我已经添加了很多。这只是一个测试函数,除了写入变量和shell之外,它实际上并没有做任何事情。一旦有效,我计划将它放在gui后面,以阻止长时间运行的任务的干扰,因为同时会有多个运行,可能需要2分钟才能完成。 – Lister