c# - 是否可以将 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# 应用程序调用它的方法?
解决方案
为了解决这个问题,我计划通过创建一个单独的可执行文件来将 powershell 会话隔离到它自己的进程中,该可执行文件接受 Powershell 命令并返回结果。这样,我可以在不使用 powershell 时关闭该进程并释放内存。
推荐阅读
- css - styled-components 切换重启动画
- php - class_exists 无法识别有效的命名空间
- nestjs - TypeORM - 左加入没有“deletedAt IS NULL”
- java - Jaxb 从具有命名空间的 XML 文件中解组 java 文件
- terraform - 是否可以将 aks 自定义标头与 azurerm_kubernetes_cluster 资源一起使用?
- c# - 如何为 C# 字典中的多个键分配一个值?
- sap-ariba - 将 cXML 发票过帐到 SAP Ariba Cloud Integration Gateway
- java - 用户可以在 jarsigner 工具 java 代码中设置私钥/公钥值吗
- python - 是否有一个 Python 函数可以对数组中的所有值求和
- r - 如何计算不同组中的嵌套类别及其在R中的平均值