更新时间:2022-11-03 20:38:23
如果要在主执行上下文和单独的运行空间或运行空间池之间共享状态,请使用SessionStateProxy
变量并分配同步的集合或字典:
If you want shared state between your main execution context and a separate runspace or runspace pool, use a SessionStateProxy
variable and assign a synchronized collection or dictionary:
$sharedData = [hashtable]::Synchronized(@{})
$rs = [runspacefactory]::CreateRunspace()
$rs.Open()
$rs.SessionStateProxy.SetVariable('sharedData',$sharedData)
$sharedData
变量现在在调用运行空间和内部$rs
The $sharedData
variable now refers to the same synchronized hashtable in both the calling runspace and inside $rs
下面是如何使用运行空间的基本说明
您可以将运行空间附加到PowerShell
对象的Runspace
属性,它将在该运行空间中执行:
You can attach a runspace to the Runspace
property of a PowerShell
object and it'll execute in that runspace:
$rs = [runspacefactory]::CreateNewRunspace()
$rs.Open()
$ps = { Get-Random }.GetPowerShell()
$ps.Runspace = $rs
$result = $ps.Invoke()
您还可以将RunspacePool
分配给多个PowerShell
实例,并使其同时执行:
You can also assign a RunspacePool
to multiple PowerShell
instances and have them execute concurrently:
# Create a runspace pool
$rsPool = [runspacefactory]::CreateRunspacePool()
$rsPool.Open()
# Create and invoke bunch of "jobs"
$psInstances = 1..10 |ForEach-Object {
$ps = {Get-Random}.GetPowerShell()
$ps.RunspacePool = $rsPool
[pscustomobject]@{
ResultHandle = $ps.BeginInvoke()
Instance = $ps
}
}
# Do other stuff here
# Wait for the "jobs" to finish
do{
Start-Sleep -MilliSeconds 100
} while(@($psInstances.ResultHandle.IsCompleted -eq $false).Count -gt 0)
# Time to collect our results
$results = $psInstances |ForEach-Object {
if($_.Instance.HadErrors){
# Inspect $_.Instance.Streams.Error in here
}
else {
# Retrieve results
$_.Instance.EndInvoke($_.ResultHandle)
}
}