You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 5.0调用Runspace.Open()卡住报PSRemotingTransportException如何解决?

问题原因

你遇到的报错和卡住问题由两个核心错误导致:

  1. 你手动提前调用了pspi.Process.Start(),CreateOutOfProcessRunspace方法内部会自动完成进程启动、通信管道初始化的全流程,手动启动进程会破坏SDK和PowerShell进程的握手逻辑,直接导致Open操作超时失败。
  2. .NET Core/5+配套的Microsoft.PowerShell.SDK默认适配跨平台的PowerShell 7+(对应程序名pwsh.exe),你强制指定了Windows PowerShell 5.1的路径powershell.exe,两者的远程通信协议不兼容,也会导致通信失败。
    .NET Framework下能运行是因为旧版System.Management.Automation本身就是Windows PowerShell 5.1的配套组件,协议匹配,且手动启动进程的操作在旧版本逻辑中未做校验。
注意事项
  • 无需单独引用System.Management.Automation包,Microsoft.PowerShell.SDK已经包含了对应版本的相关程序集,单独引用极易出现版本冲突。
  • .NET 5已经停止官方支持,建议升级到.NET 6及以上长期支持版本,同时配套升级Microsoft.PowerShell.SDK到最新稳定版。
解决方案

方案1:使用默认PowerShell 7+运行(推荐)

无需手动指定进程路径,删除手动启动进程的代码即可:

using var pspi = new PowerShellProcessInstance();
using var rs = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(Array.Empty<string>()), pspi);
rs.Open();

using (PowerShell powershell = PowerShell.Create()) {
    powershell.Runspace = rs;
    powershell.AddScript("<你的脚本内容>");
    var output = powershell.Invoke();
}

方案2:强制使用Windows PowerShell 5.1运行

如果你的脚本依赖只有Windows PowerShell 5.1才有的组件,通过配置指定使用Windows PowerShell运行时即可:

var startupInfo = new PowerShellProcessStartupInfo
{
    UseWindowsPowerShell = true
};
using var pspi = new PowerShellProcessInstance(startupInfo);
using var rs = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(Array.Empty<string>()), pspi);
rs.Open();

using (PowerShell powershell = PowerShell.Create()) {
    powershell.Runspace = rs;
    powershell.AddScript("<你的脚本内容>");
    var output = powershell.Invoke();
}

内容的提问来源于stack exchange,提问作者User404

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:12:00