2014-03-13 19 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" 
    } 
}