带有运行空间池的 SessionStateProxy 变量

SessionStateProxy Variable with Runspace Pools

我想在 PowerShell 中使用运行空间池来执行后台操作。但是我需要从主线程访问 WPF Window 变量。

普通运行空间有选项:

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

但是我如何对 RunspacePool 执行相同的操作?

将变量添加到运行空间池稍微复杂一些,但仍然绝对可行。您将需要创建一个 InitialSessionState 对象,然后创建一个包含要添加到运行空间池的变量的 SessionStateVariableEntry 对象。

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