簡體   English   中英

創建RunSpace時如何使用PowerShell 2或3?

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

在安裝了PowerShell 2.0和PowerShell 3.0的計算機上,當我創建RunSpace時如何選擇從C#應用程序啟動的計算機?

似乎有各種各樣的配置參數,但是沒有一個參數控制啟動哪個版本的PowerShell。 我可以想象它可能基於用於調用過程的.NET版本,但是當您調用RunspaceFactory.CreateOutOfProcessRunspace時呢? 那樣的話沒關系吧?

您需要使用帶有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"
    }
}

PowerShell v3附帶了System.Management.Automation.dll的新3.0版本。 您可以在啟動代碼的早期嘗試使用Assembly.Load()搶先加載3.0 SMA dll,以加載PowerShell v3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM