是否可以将Import-PSSession导入现有的“OutOfProcessRunspace”

时间:2018-05-31 20:24:29

标签: c# powershell runspace

使用下面的代码,生成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会话隔离到自己的进程并从c#应用程序调用它的方法?

1 个答案:

答案 0 :(得分:0)

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