Search code examples
c#multithreadingpowershellapartment-state

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


I have an app which runs several Powershell scripts. (It is basically a wrapper application that pulls some PS scripts stored in a SQL database and then runs them.)

One of the Powershell scripts I have added is failing now, and I have a feeling it is because it needs to run in the STA apartment state. However, I don't know how to set the apartmentstate in c#.

The function I am using is as follows:

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)
 }  
}

How can I set this to run the scripts in STA mode?


Solution

  • First, create a runspace and set the ApartmentState property:

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

    Then set the Runspace property of the PowerShell instance to use the aforementioned runspace:

    PowerShellInstance.Runspace = rs;