Posted on:
Categories: Exchange
Description:
Problem Statement:
 
The issue with provisioning Exchange 2007 objects through managed code is that the entire Exchange management console had to be installed and the managed code would then invoke the exchange powershell cmdlets through the pipeline. This presented challenges with most production systems and sys admins would not allow it. With Exchange 2010 Microsoft has changed the requirements for provisioning Exchange objects remotely and this post highlights how to provision an Exchange mailbox without the Exchange management console.
 
The action relies on Powershell 2.0 remoting which is essentially the cmdlet running remotely on an Exchange server. The standard requirements for building such code is system.management.automation which is part of Windows 2008 SDK
The sample code highlighted below is console app that binds to the Exchange 2010 RPS URI and provisions the mailbox. Any questions please drop me a note or comment:
 

static void Main(string[] args)

{

SecureString password = new SecureString();

string str_password = "xxxxxxx";

string username = "domain\admincreds";

string liveIdconnectionUri = "http://armor.softlanding.local/Powershell?serializationLevel=Full";

//secures the password

foreach (char x in str_password)

{

password.AppendChar(x);

}

PSCredential credential = new PSCredential(username, password);

// Set the connection Info

WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(liveIdconnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange",

credential);

connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;

// create a runspace on a remote path

// the returned instance must be of type RemoteRunspace

string usercommonname = "domain\\user";

string userlogonname = "firstname.lastname";

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

PowerShell powershell = PowerShell.Create();

PSCommand command = new PSCommand();

command.AddCommand("Enable-Mailbox");

command.AddParameter("Identity", usercommonname);

command.AddParameter("Alias", userlogonname);

powershell.Commands = command;

try

{

// open the remote runspace

runspace.Open();

// associate the runspace with powershell

powershell.Runspace = runspace;

// invoke the powershell to obtain the results

powershell.Invoke();

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

finally

{

// dispose the runspace and enable garbage collection

runspace.Dispose();

runspace = null;

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

// up any resources.

powershell.Dispose();

powershell = null;

}

}