How to access a different powershell runspace with

2019-08-27 02:30发布

问题:

I worked quite a bit with PowerShell runspaces and I know it's possible to invoke commands in another runspace by using a dispatcher from WPF-objects.

I create my runspaces like this:

$global:A = [hashtable]::Synchronized(@{})
$global:initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
# Add some functions to the ISS
$GuiRunspace =[runspacefactory]::CreateRunspace($initialSessionState)
$GuiRunspace.ApartmentState = "STA"
$GuiRunspace.Open()
$GuiRunspace.SessionStateProxy.SetVariable("A",$A)
$GuiRunspace.SessionStateProxy.SetVariable("B",$B) 
$GuiRunspace.Name = "GuiRunspace"

$Gui = [powershell]::Create()
[void]$Gui.addscript($GUILayerScript)
$Gui.Runspace = $GuiRunspace
$GuiThread = $Gui.beginInvoke()

And with the following code, I can manipulate that runspace from other runspaces:

$A.Window.Dispatcher.invoke({ *Do some crazy stuff that has nothing to do with the object from which you called the dispatcher* })

This only works because the window is a WPF-object that has the dispatcher property.

The question is, how do I invoke a command in other runspaces without a WPF-dispatcher?

回答1:

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)

The $sharedData variable now refers to the same synchronized hashtable in both the calling runspace and inside $rs

Below follow a basic description of how to use runspaces


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()

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)
    }
}