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