Wednesday, July 15, 2009

Programmatically creating mailbox for an existing user in Exchange Server 2010

In this post I am going to demonstrate how we can leverage the Exchange Management Shell Commandlets with managed code to accomplish some basic administrative tasks like creating mailbox in Exchange Server 2010 for existing users.

Before getting started just ensure that you have Windows PowerShell SDK installed on your development machine. Developers working on Windows Server 2008 can skip this check because Windows PowerShell is now included as part of Windows Server 2008.

In your C# project, add reference to System.Management.Automation.dll assembly. Once you install PowerShell, you will find it on the following path C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\ . Somehow I was not able to find this assembly any where in program files folder on my Windows Server 2008 machine. So I manually took the DLL out from GAC and put it in a local folder and referenced it.

Add the following directive statements to your code

using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Collections;

Next Add the following methods to your code:

  • EnableMailbox- Creates mailbox for an existing user by using the Enable-Mailbox commandlet.

In this method I am creating and opening a Runspace that has access to the Exchange Management Shell. Next is to create an object of Pipeline class by using this runspace. Before creating a mailbox, it’s good to check whether the users already has a mailbox on exchange or not. So here I am calling a method MailBoxAlreadyExist (explained in next section) which checks for the users' mailbox and returns me true or false accordingly.

Further I am creating an instance of the Command class by using the name of the cmdlet I wish to run (Enable- Mailbox). This cmdlet is then added to the command collection of pipleline object. Invoking the pipeline object would run the command and create a mailbox in exchange.

 Enable Mailbox 
  • MailBoxAlreadyExist- Checks whether the mailbox for a give user identity already exists on Exchange Server. Here I am using the Get-User commandlet to get the required user(PSObject). Next using the lambda expressions, I am checking the value of property ‘RecipientType’. If the user already has a mailbox on Exchange, then this property returns a value UserMailbox else it would return User.
The code can be downloaded from here


  1. MS Exchange is the very complicated and interesting software. But sometimes it works incorrectly. In such cases the special tools must help. One of the best programs is the next to my mind. It worked out some my problems and would overcome with almost every trouble - recover exchange ost file.