Sunday, May 23, 2010

Exchange 2010 using C# and to create mailboxes using remote shell connect

here is a nice code snippest:
SecureString password = new SecureString();

string str_password = "pass";

string username = "userr";

string liveIdconnectionUri = "http://exchange.Domain.local/Powershell?serializationLevel=Full";

foreach (char x in str_password)




PSCredential credential = new PSCredential(username, password);

// Set the connection Info

WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(liveIdconnectionUri)), "",


connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;

// create a runspace on a remote path

// the returned instance must be of type RemoteRunspace

Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);

PowerShell powershell = PowerShell.Create();

PSCommand command = new PSCommand();


command.AddParameter("Identity", usercommonname);

command.AddParameter("Alias", userlogonname);

command.AddParameter("Database", "MBX_SBG_01");

powershell.Commands = command;



// open the remote runspace


// associate the runspace with powershell

powershell.Runspace = runspace;

// invoke the powershell to obtain the results

return = powershell.Invoke();


catch (Exception ex)






// dispose the runspace and enable garbage collection


runspace = null;

// Finally dispose the powershell and set all variables to null to free

// up any resources.


powershell = null;


1 comment:

The Dutch Wing said...


Thank you very much for your post, very useful information.

A question though: is this supposed to also create the user account, or only to activate the mailbox for an account which already existed?

I tried implementing your example and I get the following error on the Exchange 2010 server:

Task Enable-Mailbox writing error when processing record of index 0. Error: Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException: The operation couldn't be performed because object '[alias]' couldn't be found on '[ExchangeDomain]'.