Search code examples
powershellrunspace

SessionStateProxy Variable with Runspace Pools


I wanted to use a Runspace Pool in PowerShell to perform Background actions. But I need to access the WPF Window Variable from the Main Thread.

Normal Runspaces have the option:

$runspace.SessionStateProxy.SetVariable('xamGUI',$xamGUI)

But how do I do the same with a RunspacePool?


Solution

  • It is a little more involved to add a variable to a runspacepool, but still definitely doable. You will need to create an InitialSessionState object and then create a SessionStateVariableEntry object that contains the variable that you want to add to the runspacepool.

    [int]$Test = 123498765
    #Create the sessionstate variable entry
    $Variable = New-object System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'Test',$Test,$Null
    $InitialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
    
    #Add the variable to the sessionstate
    $InitialSessionState.Variables.Add($Variable)
    
    #Create the runspacepool using the defined sessionstate variable
    $RunspacePool = [runspacefactory]::CreateRunspacePool(1,$Throttle,$InitialSessionState,$Host)