powershell / runspace in a thread

Posted by Vincent on Stack Overflow See other posts from Stack Overflow or by Vincent
Published on 2009-06-18T15:22:52Z Indexed on 2010/03/24 19:53 UTC
Read the original article Hit count: 676

Filed under:
|
|

Hello !

I'm running the following code :

RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException warning;
config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out warning);
if (warning != null) throw warning;            

Runspace thisRunspace = RunspaceFactory.CreateRunspace(config);
thisRunspace.Open();

string alias = usr.AD.CN.Replace(' ', '.');
string letter = usr.AD.CN.Substring(0, 1);
string email = alias + "@" + (!usr.Mdph ? Constantes.AD_DOMAIN : Constantes.MDPH_DOMAIN) + "." + Constantes.AD_LANG;
string db = "CN=IS-" + letter + ",CN=SG-" + letter + ",CN=InformationStore,CN=" + ((char)letter.ToCharArray()[0] < 'K' ? Constantes.EXC_SRVC : Constantes.EXC_SRVD) + Constantes.EXC_DBMEL;
string cmd = "Enable-Mailbox -Identity \"" + usr.AD.CN + "\" -Alias " + alias + " -PrimarySmtpAddress " + email + " -DisplayName \"" + usr.AD.CN + "\" -Database \"" + db + "\"";
Pipeline thisPipeline = thisRunspace.CreatePipeline(cmd);
thisPipeline.Invoke();

The code is running in a thread created that way :

        t.WorkThread = new Thread(cu.CreerUser);
        t.WorkThread.Start();

If I run the code directly (not through a thread), it's working.

When in a thread it throws the following exception : ObjectDisposedException "The safe handle has been closed." (Translated from french)

I then replaced "Open" wirh "OpenAsync" which helped not getting the previous exception. But when on Invoke I get the following exception : InvalidRunspaceStateException "Unable to call the pipeline because its state of execution is not Opened. Its current state is Opening." (Also translated from french)

I'm clueless...

Any help welcome !!! Thanks !!!

© Stack Overflow or respective owner

Related posts about powershell

Related posts about c#