简体   繁体   English

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

[英]How to PowerShell 2 or 3 when creating RunSpace?

On a computer with PowerShell 2.0 and PowerShell 3.0 installed, how can I select which is started from my C# app when I create the RunSpace? 在安装了PowerShell 2.0和PowerShell 3.0的计算机上,当我创建RunSpace时如何选择从C#应用程序启动的计算机?

It seems there are all kinds of configuration parameters, but none that control which version of PowerShell is started. 似乎有各种各样的配置参数,但是没有一个参数控制启动哪个版本的PowerShell。 I can imagine it might be based on the version of .NET used for the calling process, but what about when you call RunspaceFactory.CreateOutOfProcessRunspace? 我可以想象它可能基于用于调用过程的.NET版本,但是当您调用RunspaceFactory.CreateOutOfProcessRunspace时呢? In that case, it shouldn't matter, right? 那样的话没关系吧?

You need to use the overload of CreateOutOfProcessRunspace that takes a PowerShellProcessInstance, and you need to specify the version when creating the PowerShellProcessInstance. 您需要使用带有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"
    }
}

There is a new 3.0 version of System.Management.Automation.dll that PowerShell v3 shipped with. PowerShell v3附带了System.Management.Automation.dll的新3.0版本。 You could try preemptively loading the 3.0 SMA dll using Assembly.Load() early in your startup code to cause PowerShell v3 to be loaded. 您可以在启动代码的早期尝试使用Assembly.Load()抢先加载3.0 SMA dll,以加载PowerShell v3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM