2017-03-23 128 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;