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

915 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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;