2014-03-13 21 views
1

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

似乎有各种配置参数,但没有哪个控制哪个版本的PowerShell启动。我可以想象它可能基于用于调用过程的.NET版本,但是当您调用RunspaceFactory.CreateOutOfProcessRunspace时呢?在这种情况下,这应该不重要,对吧?

+0

*可能*是[this](http://stackoverflow.com/q/16148305/21567)的副本。 IOW,PowerShell版本绑定到.NET版本。你必须在你的app.config中指定你支持的哪个.NET版本,以及你得到的PS版本。 –

+0

这是有道理的,除非PowerShell启动过程中。然后我会认为你可以重视。 – DougN

回答

1

PowerShell v3附带的System.Management.Automation.dll有一个新的3.0版本。您可以尝试在启动代码的早期使用Assembly.Load()预先加载3.0 SMA dll,以便加载PowerShell v3。

3

您需要使用接受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" 
    } 
}