首页 > 解决方案 > 是否可以将 PSSession 导入现有的“OutOfProcessRunspace”

问题描述

使用下面的代码,会生成一个 powershell 进程并正确打开运行空间。从这里我可以提交 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 会话隔离到自己的进程中并从 ac# 应用程序调用它的方法?

标签: c#powershellrunspace

解决方案


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


推荐阅读