【问题标题】:How can I set the runspace of PowerShell code I am running from c#?如何设置从 c# 运行的 PowerShell 代码的运行空间?
【发布时间】:2017-03-23 12:55:02
【问题描述】:

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

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

【问题讨论】:

    标签: c# multithreading powershell apartment-state


    【解决方案1】:

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

    using System.Threading;
    using System.Management.Automation.Runspaces;
    // ...
    
    Runspace rs = RunspaceFactory.CreateRunspace();
    rs.ApartmentState = ApartmentState.STA;
    

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

    PowerShellInstance.Runspace = rs;
    

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      相关资源
      最近更新 更多