且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有WPF对象的情况下访问不同的Powershell运行空间

更新时间: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)
    }
}