2017-03-23 33 views
0

我有一個運行幾個Powershell腳本的應用程序。 (它基本上是一個包裝應用程序,它將一些PS腳本存儲在SQL數據庫中,然後運行它們。)如何設置我從c#運行的PowerShell代碼的運行空間?

我添加的Powershell腳本之一現在失敗了,我有一種感覺,因爲它需要運行在STA公寓狀態。但是,我不知道如何在c#中設置公寓狀態。

我使用的功能如下:

public bool RunSomePowershell(string script) 
{ 
using (PowerShell PowerShellInstance = PowerShell.Create()) 
{ 
    PowerShellInstance.AddScript(script); 
    var result = PowerShellInstance.Invoke(); 
    return Convert.ToBoolean(result[result.Count -1].ToString()); // Result should be last output from script (true or false) 
} 
} 

我怎樣才能將其設置爲運行在STA模式的腳本?

回答

2

首先,創建一個運行空間並設置ApartmentState屬性:

using System.Threading; 
using System.Management.Automation.Runspaces; 
// ... 

Runspace rs = RunspaceFactory.CreateRunspace(); 
rs.ApartmentState = ApartmentState.STA; 

然後設置PowerShell實例的Runspace財產使用上述運行空間:

PowerShellInstance.Runspace = rs;