【问题标题】:.NET Core 5.0 Runspace.Open() doesn't work.NET Core 5.0 Runspace.Open() 不起作用
【发布时间】:2021-10-30 03:32:40
【问题描述】:

我正在尝试启动一个 Runspace 实例来启动一些 Powershell 命令。但是如果我使用“runspace.Open()”方法,程序就会卡住。一段时间后,该方法失败并显示错误消息:

System.Management.Automation.Remoting.PSRemotingTransportException HResult=0x80131501 
Nachricht = The background process reported an error with the following message: D 
Quelle = System.Management.Automation

这是对应的代码行:

Runspace rs;
var pspi = new PowerShellProcessInstance();
pspi.Process.StartInfo.FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
pspi.Process.Start();
rs = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), pspi);
rs.Open();

using (PowerShell powershell = PowerShell.Create()) {
    powershell.Runspace = rs;
    powershell.AddScript(<some code>);
    var output = powershell.Invoke();
}

我正在使用 .NET Core 5 控制台应用程序和以下软件包:

  • Microsoft.PowerShell.SDK
  • System.Management.Automation

如果我在 .NET Framework 控制台应用程序中运行相同的代码,则一切正常。有什么解决这个问题的建议吗?

【问题讨论】:

    标签: c# .net visual-studio powershell


    【解决方案1】:

    解决方案是使用 PowerShellProcessInstance 的参数化构造函数,因此,在服务器模式下启动 Powershell:

    Version psVersion = new Version("5.1");
    TypeTable type = new TypeTable(new string[0]);
    
    powershellInstance = new PowerShellProcessInstance(psVersion, null, null, false);
    powershellInstance.Process.StartInfo.FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
    
    runspace = RunspaceFactory.CreateOutOfProcessRunspace(type, powershellInstance);
    runspace.Open();
    

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 2021-03-09
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多