创建 RunSpace 时如何使用 PowerShell 2 或 3?

Dou*_*ugN 3 .net c# powershell runspace

在安装了 PowerShell 2.0 和 PowerShell 3.0 的计算机上,创建 RunSpace 时如何选择从 C# 应用程序启动哪个?

似乎有各种各样的配置参数,但没有一个控制启动哪个版本的PowerShell。我可以想象它可能基于用于调用进程的 .NET 版本,但是当您调用 RunspaceFactory.CreateOutOfProcessRunspace 时会怎么样?既然如此,应该没什么关系吧?

Jam*_*cia 6

您需要使用带有 PowerShellProcessInstance 的 CreateOutOfProcessRunspace 重载,并且需要在创建 PowerShellProcessInstance 时指定版本。

PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(2, 0), null, null, false);
using (Runspace rs = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance))
{
    rs.Open();
    using (PowerShell ps = PowerShell.Create())
    {
        ps.Runspace = rs;
        ps.AddScript("$PSVersionTable");

        dynamic vt = ps.Invoke().Single();

        Console.WriteLine(vt.PSVersion); // This will output "2.0"
    }
}
Run Code Online (Sandbox Code Playgroud)