Author Posts

March 30, 2016 at 11:26 am

I have an application hosting powershell, everything is running in a background worker and until now everything was ok 🙂
The code looked like this

Runspace space = RunspaceFactory.CreateRunspace(this); 
// this -> a class derived from PSHost
space.ApartmentState = System.Threading.ApartmentState.STA;
space.ThreadOptions = PSThreadOptions.UseCurrentThread;
space.Open();                

Now I wanted to add a possibility to import modules. So I decided to use InitialSessionState. I changed my code to this:

InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(...);

Runspace space = RunspaceFactory.CreateRunspace(this, iss); 

space.ApartmentState = System.Threading.ApartmentState.STA;
space.ThreadOptions = PSThreadOptions.UseCurrentThread;
space.Open();                

So, basically I used an other overload of CreateRunspace using the InitialSessionState too.
But now I am getting an System.InvalidOperationException in the line space.Open().

I try to translate from german to english:
If the Runspace is set to use the current thread, the state apartment in the call settings must correspond to the current thread.

grateful for any help

April 13, 2016 at 5:54 am

Unfortunately, we don't have a big audience here who's working with PowerShell in this way. Apologies that you haven't been able to get an answer; I'm hoping you'll consider trying on someplace like StackOverflow, which tends to get a bigger Dev audience, or in the #powershell channel on IRC, which also has a much bigger Dev audience.