是否可以将 Import-PSSession 导入现有 "OutOfProcessRunspace"

Is it possible to Import-PSSession into existing "OutOfProcessRunspace"

使用下面的代码,生成一个 powershell 进程并正确打开 运行space。从这里我可以提交 powershell 命令来创建和导入远程 powershell 会话。问题是这个新会话将所有导入的模块加载并缓存到主机进程中,而不是 CreateOutOfProcessRunspace(...).Open() 生成的进程,无法对缓存的模块进行垃圾收集。

PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(5, 1), null, null, true);
var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance);
runspace.Open();

使用 powershell 实例的初始化脚本卡在 runspace.Open()。据我所知,它甚至从未超时。我让它 运行 持续了整整 5 分钟(此时拉出远程模块的时间不应超过 20 秒),运行 空间的状态仍然是 Opening

string script = string.Join("\r\n", new string[] {
    "$Username = \"mailbox\"",
    "$SecurePass = ConvertTo-SecureString -AsPlainText password -Force",
    "$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecurePass",
    "$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "url" -Credential $Credential -Authentication Basic -AllowRedirection",
    "Import-PSSession $session"
});

PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(5, 1), null, ScriptBlock.Create(script), true);
var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance);
runspace.Open();

有谁知道将远程 powershell 会话隔离到它自己的进程中并从 c# 应用程序调用它的方法吗?

为了解决这个问题,我计划通过创建一个单独的可执行文件来将 powershell 会话隔离到它自己的进程中,该可执行文件接受 Powershell 命令和 returns 结果。这样我就可以在不使用 powershell 时关闭该进程并释放内存。