InvalidOperationException on Runspace.Open();

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 8 months ago.

  • Author
    Posts
  • #37112
    Profile photo of Alexander Knopp
    Alexander Knopp
    Participant

    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

  • #37649
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

You must be logged in to reply to this topic.