我如何从 c# 运行 设置 PowerShell 代码的运行空间?

How can I set the runspace of PowerShell code I am running from c#?

我有一个应用程序,其中 运行 有几个 Powershell 脚本。 (它基本上是一个包装器应用程序,它提取存储在 SQL 数据库中的一些 PS 脚本,然后 运行s 它们。)

我添加的一个 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 模式下的脚本?

首先,创建一个运行空间并设置 ApartmentState 属性:

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

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

然后设置 PowerShell 实例的 Runspace 属性 以使用上述运行空间:

PowerShellInstance.Runspace = rs;