Enterprise Powershell: Creating Mailboxes in Exchange 2003

This articles focus on the increasingly popular Powershell command line shell and scripting language that runs on existing and future Microsoft infrastructure environments. We'll presume you are familiar with Powershell and have it installed and tested on your systems. If not, we encourage you to read an introductory article that will get you up to speed quickly.

Using Powershell with Exchange 2003

Let's consider a common mid-sized Microsoft IT environment for today with a few hundred mail-enabled active directory users. In this case, for email services you are a developer or systems administrator working with Exchange 2003 running on Windows Server 2003 who is using Powershell today in preparation for your future scripting needs with Exchange 2007 running on Windows Server 2008. Although there are a number of great ways Exchange 2007 and Powershell integrate, you must deal with a few hurdles in scripting Powershell and Exchange 2003 today. Specifically, you still must use CDOEXM as the fundamental component object model and interfaces used to manage the Exchange 2003 store.

As an Exchange 2003 developer or administrator, you are undoubtedly familiar with programming for the CDOEXM IMailboxstore interface and of course calling CreateMailbox. In fact, the Microsoft.com knowledgebase has a great article on how to accomplish this with C#. However, this is Powershell and if you have tried to translate the same examples you have probably received a message such as "Cannot load COM type CDOEXM.IMailBoxStore." We're going to show you how to get around this error by using CDOEXM through assembly reflection and late binding. If those two concepts escape your immediate memory, remember that assembly reflection is a way to view classes exposed from the assembly and late binding is binding to an object late as possible; this is most commonly just before it's called (run-time dynamic linking).

Powershell Mailbox Creation Script

Start with an initial snippet from your Powershell and Exchange 2003 script. Here, you are starting the script header and establishing default variables for Active Directory connectivity, domain query filter, and default exchange mail store. When searching for users, you are looking for all users in the domain who do not have their homeMDB property set—the message database where the mailbox is allocated. Keep in mind you'll want to tailor the filter criteria for your local policy where, commonly, only certain groups of users have mail-enabled accounts.

#
# Powershell and Exchange 2003 Mailbox Creation
#

#
# ACTIVE DIRECTORY DOMAIN CONNECTION
#

$DOMAIN                          = "LDAP://dc3.example.com:389"
$DOMAIN_USER_BASE                = ""
$DOMAIN_SERVICE_ACCOUNT          = "exchangemanager"
$DOMAIN_SERVICE_ACCOUNT_PASSWORD = "XXXXXXXXX"
$DOMAIN_SEARCH_FILTER            = "(&(objectClass=user)(!homeMDB=*))"

#
# EXCHANGE 2003 MAIL STORES
#

$EXCHANGE_MAILSTORE =  "CN=PEOPLE,CN=First Storage Group,
                        CN=InformationStore,CN=EXCHMAIL0,CN=Servers,
                        CN=First Administrative Group,
                        CN=Administrative Groups,CN=EXAMPLECORP,
                        CN=Microsoft Exchange,CN=Services,
                        CN=Configuration,dc=example,dc=com";

Next, you have a set of references to CDOEXM that becomes a key point of the script. Here, you are loading the CDOEXM.dll, assigning the CDOEXM.IMailboxStore type to a variable, and setting the binding flags for invoking member methods. What this sets you up for is calling the CDOEXM createmailbox method.

#
# CDOEXM REFERENCES
#

$ASSEMBLY      = [Reflection.Assembly]::LoadFile
                 ("C:\pscripts\Interop.CDOEXM.dll")
$ASSEMBLY_TYPE = $ASSEMBLY.GetType("CDOEXM.IMailboxStore")
$BINDING_FLAGS = [Reflection.BindingFlags] "invokemethod,public"

Now, you query the Active Directory server for all users matching the specified filter.

#
# QUERY ACTIVE DIRECTORY USERS WHO DO NOT HAVE A MAILBOX
#

$domain_query = new-Object System.DirectoryServices.DirectorySearcher
$domain_query.searchroot =
   New-Object System.DirectoryServices.DirectoryEntry
   ("$DOMAIN/$DOMAIN_USER_BASE", $DOMAIN_SERVICE_ACCOUNT,
     $DOMAIN_SERVICE_ACCOUNT_PASSWORD)
$domain_query.pagesize    = 1000
$domain_query.searchscope = "subtree"
$domain_query.filter      = $DOMAIN_SEARCH_FILTER

$people = $domain_query.findall()

Finally, you loop though the query results and invoke CDOEXM's createmailbox on each user, printing an error or success result, and dispose of allocated resources. When invoking createmailbox, you'll notice that one of the usage of .PSBase; this is important because it allows you to access the underlying .NET ADSI native object.

#
# LOOP THROUGH EACH PERSON IN THE QUERY RESULT
#

foreach($person in $people)
{
   $mailstore = $EXCHANGE_MAILSTORE
   [string]$dn = $person.properties.distinguishedname
   $domain_person=
      New-Object System.DirectoryServices.DirectoryEntry
      ("$DOMAIN/$dn", $DOMAIN_SERVICE_ACCOUNT,
        $DOMAIN_SERVICE_ACCOUNT_PASSWORD)

   #create the mailbox
      (CDOEXM.IMailboxStore:
       http://msdn2.microsoft.com/en-us/library/aa487566.aspx)
   $ASSEMBLY_TYPE.invokemember("createmailbox",$BINDING_FLAGS,
      $null,$domain_person.psbase.nativeobject,$EXCHANGE_MAILSTORE)

   $domain_person.psbase.commitchanges()

   if($domain_person.homeMDB -ne $null)
   {
      #force AD user update
      $domain_person.psbase.commitchanges

      #print the success
      Write-Host "Success: $dn"
   }
   else
   {
      #print the failure
      Write-Host "Error: $dn"
   }
   #close connections
   $domain_person.dispose | out-null
}

#
# CLOSE THE OPEN DOMAIN CONNECTION
#

$domain_query.dispose | out-null

The following figure shows output of the script.

Conclusion

Now that you have seen how it's possible to create user mailboxes with Powershell, the door is now wide open to use CDOEXM to manage other facets of your Exchange 2003 servers such as deleting and moving mailboxes. As a developer or administrator who is gearing towards a migration from Exchange 2003 to Exchange 2007, this is a prime opportunity to get your hands on Powershell today and make your future development work much more productive and efficient. If you build further on what you've learned here, please let us know by emailing jonATshoberg.net.

About the Authors

Jon Shoberg is a senior developer for the Fisher College of Business at The Ohio State University. He has extensive experience in developing enterprise systems in e-commerce, web, and search domains on the LAMP, Java, and .NET platforms. Jon has previously contributed to books and industry publications as a technical reviewer and coauthor, respectively.

Eddie Willett is an independent consultant specializing in Microsoft technologies. Powershell has become a recent favorite of his and would love to hear your feedback: eddieATshoberg.net.



Comments

  • after i bought the clarisonic from david jones

    Posted by iouwanzi on 06/06/2013 12:49am

    [url=http://www.miaclarisonicaustralia.org/clarisonic-mia]clarisonic mia[/url] Souvent, vous pourriez certainement blâmer la médecine. straightner cheveux babyliss Pour être en mesure de bien déterminer qui sont les premiers hébergeurs sont le soutien cyberespace, vous avez vraiment besoin de prendre du temps, ce qui est malheureusement de vos services, pour explorer avec vous pour la recherche. [url=http://www.australiaclarisonic.com/]clarisonic australia[/url] Mon conjoint et moi avons eu déplacés pour vous aux Etats-Unis pour obtenir un douze mois, ainsi que mon ghd Midnight styler Aussie ne pouvez pas travailler ces (différence de puissance et aussi une chose, l’idée ne réchauffer). Donc j’ai simplement souhaité un bon plus peu coûteux mais néanmoins fine lisseur pour l’année civile, ou peut-être que je peux accumuler plus un utilisent également (à base de plantes fumer juridique bourgeons aller à travers les États-Unis pour aider Aus est très bien mais pas l’autre option). Mon conjoint et j’ai vécu une australienne ghd Midnight styler à peu près 5 ans en ce moment et il fonctionne également comme bon comme le matin, j’ai acheté l’idée. 5 ans!! [url=http://www.australiaclarisonic.com/clarisonic-classic]clarisonic classic[/url] Cette approche ependant, juste pour un grand nombre de périodes à l’heure actuelle, toute l’entreprise collabore utilisant Jesse Lachapelle en raison des activités de publicité. (Queuwaaa ? Vous voulez ne sont pas au courant Jesse Lachapelle ? Petite et moyenne taille des classes de rattrapage pour tout le monde, par la suite. Fichier de l’ordinateur à ce moment, jeune padawan ! ) #) Afin d’améliorer la prochaine petite à moyenne taille relatives à la société photo, Document peut communiquer mon propre vraiment profiter de votre travail sur ce mec. Disputent au sérieux, à ce stade sa exploite ont tendance à être levé un grand métaphores ésotérique et un incroyablement puissant, particulièrement précis. Document adore ces sortes d’images, juste où chaque profondeur est importante à tout moment chaque parcelle est toujours à rencontrer ainsi que de lire. Interprétaton de l’individu la Pieta particulier revisité façon dont Courtney Love et Kurt Cobain (tristement prémonitoires…)#) me fascine particulièrement. Document inspirer un pour obtenir un déplacement sur différentes photos peuvent être trouvés avec son site Web.

    Reply
  • Nike Wind Max+instagram, wishes you hold the color to wear on your feet!

    Posted by madytreathy on 04/21/2013 04:51pm

    Call to mind in 2008, if not earlier, when Nike launched winning of the self-assured shoe color projects, the war cry "Whiz Your Colours", "Nike PhotoiD" scheme, [url=http://markwarren.org.uk/goodbuy.cfm]nike free uk[/url] effect has not been as hearty as expected. Have in mind, 2008 Canon IXUS 80 IS Digital file card arcade but contrariwise 8 million pixels, Nokia, the mobile phone superstore is the at worst governorship, NikeiD was support to color in the photos as a essence in return sneakers levy color, although gripping, but does provoke some. Instagram which communicate this thing make sport and modest, Nike PHOTOiD homeopathic upgrade customization services, recently [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] released a fresh plan. That such iD can you realize pictures as instagram account shoe color, temporarily offer Nike Mood Max shoes and Nike Puff Max 1, Nike Show Max 90 953 options. Interested in children's shoes, you [url=http://northernroofing.co.uk/roofins.cfm]nike free run[/url] can every associate with's official website photoid.Nike.com, in reckoning to flip other people's artistic industry, or you can hear to upload your own instagram photo, erect your own Nike Air Max.

    Reply
  • Question

    Posted by Sergey on 04/23/2012 10:23pm

    I do not understand what is (CDOEXM.IMailboxStore: http://msdn2.microsoft.com/en-us/library/aa487566.aspx) ?? It is not working with theese strings.

    • Can this be done for Exchange server 2010?

      Posted by Prad on 01/24/2013 04:28pm

      Hi, I'm using cdoexm.dll library in my vb6 code for creating mailboxes and stuff for exchange server 2003. Now we are moving to exchange server 2010 I'm sure existing code wont work. So can you please quite me what changes i need to make to make it work for 2010. Is there any powershell script that i can use?

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • "Security" is the number one issue holding business leaders back from the cloud. But does the reality match the perception? Keeping data close to home, on premises, makes business and IT leaders feel inherently more secure. But the truth is, cloud solutions can offer companies real, tangible security advantages. Before you assume that on-site is the only way to keep data safe, it's worth taking a comprehensive approach to evaluating risks. Doing so can lead to big benefits.

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds