Using Powershell to import contacts into Exchange and Outlook Live

When performing migrations between different systems, there’s always the case where the tools available don’t do the job out of the box – and although IMAP migration tools for Exchange and Outlook Live can be great for moving mail, there isn’t a decent free solution for importing contacts.

For a recent migration from a Unix system (Dovecot + SquirrelMail) to Outlook Live, I came across this very scenario. While Microsoft provide IMAP migration tools to move mail to Outlook Live (which I was lucky enough to beta test before it was widely available), no tools are provided to move other data such as contacts and calendars.

While this isn’t the actual code I used (I wrote my original code in C#), I’ve re-visited what I’ve done and listened to what others say they need. What I’ve heard is it would be useful to have some Powershell code that out-of-the box can import contacts into any Exchange mailbox. The reason that Powershell is the right language for code like this is that it’s fairly easy for the enterprising administrator to modify to their needs.

Getting started

Before you can run this script, there are a few things you need to set up first. Don’t worry though! It’s nothing too onerous – all is needed to get going is two things:

  1. Setup of EWS  impersonation, unless you only want to work with accounts you know the username/password for.
  2. Installing the Managed API DLL onto your computer.

Setup of Exchange Web Services Impersonation
Exchange Web Services is the programmatic interface to each user’s Exchange mailbox. Most actions that can be performed in Outlook can be performed via EWS – so much so, in fact, that Apple’s Mail.app in Snow Leopard and the latest update for Entourage 2008 use EWS as the backend for the mail clients themselves.

If you’re planning on doing a mass-import of contacts, or don’t know the user’s password you’re importing, then setup of EWS impersonation is the step you need to take to allow a trusted account to switch to the user you want to import.

In Exchange 2010, setup of Exchange impersonation is managed via RBAC. Full details of how to setup impersonal are on the Microsoft site, but if you just want to get it setup for a single admin/service account, org-wide, use the following command substituing serviceaccount for your service account:
New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:serviceaccount
On Exchange 2007, it’s very different, and is managed by AD permissions on individual Client Access Servers. Again – full details on the Microsoft site, but to add the permission to all CAS servers, the following code will suffice, again substituting serviceaccount for your Service account:
Get-ExchangeServer | where {$_.IsClientAccessServer -eq $TRUE} | ForEach-Object {Add-ADPermission -Identity $_.distinguishedname -User (Get-User -Identity serviceaccount| select-object).identity -extendedRight ms-Exch-EPI-Impersonation}

Installing the Exchange Web Services Managed API
Next, whatever environment you are in, you need a copy of the DLL file that provides the bits and pieces that make this all work. The easiest way to get up and running is to download the API (choosing the right version for your platform), and install it to it’s default location.

Download the EWS Managed API v1.2 from the Microsoft site

Once downloaded and installed, you should be good to go with script.

Using the script Import-MailboxContacts.ps1

So, you’ve got impersonation setup if needed, got the EWS DLL on your machine. You should be good to go!

For each mailbox you want to import contacts from you need a separate CSV file. The format of the file is intentionally the same as Outlook will export in, mainly because a lot of apps already export in the format (Gmail does, for example) so you should find it easy to get test data, but if you haven’t I’ve included a sample file to get you started.

Along with the data, you also need, at a minimum, the mailbox email address to import to. This is used when impersonating, and for Autodiscover. If you’re not logged on as the user you want to use for the import, you can specify a username and password. Additionally, there’s a variety of options to specify the EWS Url manually, switching to the Exchange 2007 version of the API etc.

Examples

The first example is a straightforward import into the current logged-on user’s mailbox. We’re specifying the Email Address and the URL to EWS (to bypass Autodiscover):

image

.\Import-MailboxContacts.ps1 -CSVFileName .\Contacts.csv -EmailAddress steve@goodman.net -EwsUrl https://server/EWS/Exchange.asmx

As you can see in the above example – it’s all fairly straightforward. You’ll also see the output shows the contacts that have been created – you can use standard Powershell pipeling to export this data, pipe it to another command or filter it.

The second example is slightly more complicated, and reflects the main use case. We’re connecting to a remote exchange organisation, using Autodiscover to find the EWS address, enabling impersonation and providing credentials at the command line:

image

.\Import-MailboxContacts.ps1 -CSVFileName .\Contacts.csv –EmailAddress steve@contoso.com -Impersonate $true -Username serviceaccount -Password password -Domain contoso

In addition to the options above, you can also specify the parameters -Exchange2007 $true and use -EWSManagedApiDLLFilePath to specify a different path the the EWS DLL.

Powershell Code

Finally, you’ll need a copy of the code to do all this. Below you’ll find a ZIP file containing the Import-MailboxContacts.ps1 file and a sample CSV file. Happy importing!

Download as ZIP

84 thoughts on “Using Powershell to import contacts into Exchange and Outlook Live

  1. Never mind, I forgot the “impersonate” piece,

    BUT (and there’s always a ‘but’), as other users have stated, this would be great to modify so that it does NOT create duplicates! If you run this a 2nd (or subsequent) time, it just makes duplicates each time of all the same contacts. I guess the check could be “If [existing first-name+last-name = new first-name+last-name], then detele existing contact, then update new contact.” Better still, have it modify ONLY the sections of the contact that have changed. In our case, we may in fact have more than one contact with same first name + last name – i.e., “Robert Downy” and “Robert Downy Jr.” (same first+last, but with a suffix “Jr.”), so, the question remains, how do we modify it to prevent duplicates? I might take on that exercise.

  2. I still cannot get it to work. I loaded the EWS msi piece on my worksation, where I have Exchange 2010 tools installed. Then issued the ‘role’ command – New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:serviceaccount
    (with a specified service account. But, what if it is a ‘domain’ service account, do i need “domain\serviceacct?”) – if so, can I just re-run that “New-ManagementRoleAssignment command specifying the domain-level account?
    Okay, then I executed the import:
    .\Import-MailboxContacts.ps1 -CSVFileName .\Contacts.csv -EmailAddress test01@mydoamin.org
    It displays the 3 contacts from my csv, with no errors, but I cannot find them in my “test01″ account.
    Any help would be greatly appreciated. BTW, THANK YOU for this wonderful script.

  3. Sir, I am trying to make this work with office 365 however it will not work . I get the autodiscover error do you know if this will work with office 365? I was using this script to debug another script you wrote to get headers from email, but sadly same autodiscover error. I am thinking that EWS library wont work with office 365. I am on Wave 15. This would be great if it does work with 365 Good articles and I enjoy reading them.

  4. Great script. It does almost exactly what I needed. However, does someone know if, once the new contact.. folder is created in some user malbox, there is a way to prevent the user to add some info related to those contacts? Since the folder will be rebuit from scratch every night, I would not want any user to manually add data into it… Thanks.

  5. This is probably the only useful solution I have found for using powershell to import contacts into exchange (convenient title), and for that I thank you. But, as others have mentioned, do you have any plans to update this with skip/overwrite/merge options in the near future? It would also be very helpful to see a script for exporting a user’s contact list to a csv file. If you have no intention of updating this article, could you recommend a site where I might find this information?

  6. Does this work for Office365?
    i get error: Exception calling “Bind” with “2″ argument(s): “The request failed. The remote server returned an error: (401) Unauthorized.”

    I am using the ewsurl switch because of the redirect error.

  7. Pingback: Office 365 for education - available now! - Page 4

  8. Your script saved my life!! Congratulations !! — it is simple straight forward and a great demonstration of both the power of PowerShell and the power of EWS … I was in utter amazement at the fact that this can be done from the client. I did not use impersonation (just provided username and password for each of the users to import the csv into). I’m assuming you know that **None of the major migration tools** (i.e migrationwiz) has the ability to migrate an addressbook from an imap or pop3 based system into exchange. Congrats on great work!!!

  9. Hallo Steve,
    I have problem on Exchange 2010 SP2 RU2.
    This error is
    Exception calling “Bind” with “2″ argument(s): “The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”
    At C:\ContactTest\Import-MailboxContacts.ps1:172 char:81

  10. Hallo Steve,
    I have problem on exchange 2010 SP 2 RU 2
    This error is
    Exception calling “Bind” with “2″ argument(s): “The request failed. The underlying connection was closed: Could not est
    ablish trust relationship for the SSL/TLS secure channel.”
    At C:\ContactTest\Import-MailboxContacts.ps1:172 char:81

  11. Hi Steve,

    thanks for the script. Doing its job mainly quite well the field “body” is not filled in my case. All other fields work.

    Is this a problem with my system or is this not working anyway? (I tried EWS 1.1 and 1.2)

    • It seems that its a problem with olk 2003.

      The commad seems to work it doesn’t report an error and – with owa the body is there.

      Very strage – in olk2003 the body stays empty.

      • It seems to be a Problem in OLK2003 without SP. I install SP3 for OLK and now the text in the body of the contact is visible.

  12. Pingback: Importing Global Address List entries into a user’s Contacts folder | Steve Goodman's Exchange Blog

  13. I seldom leave comments, however I browsed some remarks here Using Powershell to import contacts into Exchange and Outlook Live | Steve Goodman’s Exchange Blog. I actually do have a couple of questions for you if you tend not to mind. Is it simply me or do some of the responses appear like they are written by brain dead individuals? :-P And, if you are writing at additional online sites, I would like to follow you. Would you list of all of your shared sites like your twitter feed, Facebook page or linkedin profile?

  14. Hi guys
    how good I found here with a lot of expert persons , bcz I’m really beginner in exchange.
    I’ve recently migrated from qmail to exchange, so as you mentioned contacts aren’t migrated.
    I did exactly like what you wrote above but I got error (I used administrator user , however I have username and password for mailbox if it’s needed)
    I wrote this command:
    .\Import-MailboxContacts.ps1 -CSVFileName “C:\e.sadegh.csv” -EmailAddresse.sadegh@domain.com -Impersonate $true -Username xadmin -Password 123456 -Domain domain.com
    and get this error:
    Exception calling “AutodiscoverUrl” with “1″ argument(s): “The Autodiscover service couldn’t be located.”
    At C:\Program Files\Microsoft\exchange server\V14\Scripts\Import-MailboxContacts.ps1:159 char:33
    + $service.AutodiscoverUrl <<<< ($EmailAddress);
    + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : DotNetMethodException

    should I use "-EwsUrl https://172.25.25.20/EWS/Exchange.asmx&quot; in command? I used but got error again …

    • You need to use the direct link to EWS, as Steve noted, do this by using the switch Steve built in:
      -EWSUrl https://servername.domain/EWS/Exchange.asmx

      I have a very strange problem, I was using the script all was going well, I could import some example csv’s and was tuning the script (location, attributemappings etc). After a while I was no longer able to run the commands, I got the same error as people that were replying before:
      Exception calling “Bind” with “2″ argument(s): “The request failed. The remote server returned an error: (401) Unauthor
      ized.”
      At C:\CSV-Import\Fullscript-v1\Import-MailboxContacts-FINAL.ps1:133 char:81
      + $ContactsFolder = [Microsoft.Exchange.WebServices.Data.ContactsFolder]::Bind <<<< ($service, [Microsoft.Exchange.
      WebServices.Data.WellKnownFolderName]::Contacts);
      + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
      + FullyQualifiedErrorId : DotNetMethodException

      Anyone have an idea why this is happening?

      • In addition to this, the fault mentioned above was caused by the following:
        I did not use the following command upfront, in my case it was needed every time:
        New-ManagementRoleAssignment -Name:ImpersonationAssigmentName -Role:ApplicationImpersonation -User:[emailaddressofimpersonateduser]

        After that it worked again.
        Thanks Steve for the perfect setup!

        • And a last comment. The reply above can be ignored, this was not the problem.
          When scripting these kinds of actions it appears the O365 server needs to catch it’s breath after each action. The things I found out:
          - Make sure you are on a stable connection
          - Put delays (code “Start-Sleep -Seconds 1″) between actions such as impersonating a user, binding the contacts folder, creating a folder, creating a contact etcetera.

          After sticking to both of the above I saw no more 401′s :)
          Best of luck to you all and thanks again Steve.

  15. Thank you! This script is fantastic and works perfectly, but I was asked to also pull in Categories as well. I added the colum to my CSV and added:

    “CATEGORY” = “Item:Categories”
    It doens’t seem to be importing them. Any idea of what I’m missing?

  16. Hello,

    Thank you for writing a script to do exactly what I need. As Richard Bunch and BigVin above him have stated about the newer EWS path, I updated the path in the script to be 1.1. I setup the impersonation for the original administrator account for the Live@edu domain that I was connecting to and this was accepted. I used the pod address for my connection as Richard suggested as autodiscovery did not work and also the -domain switch; I had to use my domain suffix for the user I was targeting. However I get the same error as Bigvin; I was adding contacts to the administrator account contacts, as the administrator.

    If I use import-contactslist with a csv file then the contacts get imported, however they do not show up under the contact list, only the contacts folder.

    import-contactlist -CSV -CSVData ([System.IO.File]::ReadAllBytes “D:\Live@edu\schoolname\contacts\contacts.csv”)) -Identity administrator@schooldomain.sch.uk

    Below is the error that I get from your script:

    Exception calling “Bind” with “2″ argument(s): “The request failed. The remote
    server returned an error: (401) Unauthorized.”
    At D:\Live@Edu\Scripts\Import-MailboxContacts.ps1:172 char:81
    + $ContactsFolder = [Microsoft.Exchange.WebServices.Data.ContactsFolder]::B
    ind <<<< ($service, [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::
    Contacts);
    + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : DotNetMethodException

    This is a connection to Live@edu from a Windows 7 SP1 Pro 32bit machine.

  17. Steve,
    Great script. You mentioned earlier about adding support for importing groups also. I have a customer with a lot of users who have been using personal groups in their previous mail system. The groups can be exported to CSV files. Is it possible to extend the script?

    Regards,
    Richard

  18. Thank you for this script… I was able to run it sucessfully with Exchage 2007, but having some issues while running against exchange 2010 servers. Getting below exeption message, any help will be highly appreciated.

    ————–
    Exception calling “Bind” with “2″ argument(s): “The SMTP address has no mailbox associated with it.”
    At D:\Import-MailboxContacts\Import-MailboxContacts.ps1:172 char:81
    + $ContactsFolder = [Microsoft.Exchange.WebServices.Data.ContactsFolder]::Bind <<<< ($service, [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts);
    + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : DotNetMethodException
    —–

  19. Steve,

    Thanks this is a life saver. We are a small company with just 3 people and this is awsome!! Was wondering, if you have a script that can allow me to add external contacts through a csv file, so that these external contacts are available to all e-mail users in the company.

    I am not a IT guy and would not know how to modify the script you have provided to update the contacts for each mailbox. Any help would be appreciated…..

    PS: We just enrolled into the Office 365 program…… Plan E3 beta…….

    Pinakin

  20. Steve,

    Thanks this is a life saver. We are a small company with just 3 people and this is awsome!! Was wondering, if you have a script that can allow me to add external contacts through a csv file, so that these external contacts are available to all e-mail users in the company.

    I am not a IT guy and would not know how to modify the script you have provided to update the contacts for each mailbox. Any help would be appreciated…..

    Pinakin

  21. If you run this script several times against the same mailbox, it will create multiple copies of each contact in the .csv file. Can it be made to only update fields from the CSV file but leave everything else in the contact the same?

  22. Is there a way to use the 2010 EWS without SSL/TLS Cerificate?
    Trying to use the script but failing with:
    Exception calling “Bind” with “2″ argument(s): “The request failed. The underlying connection was closed: Could not est
    ablish trust relationship for the SSL/TLS secure channel.”
    At C:\ContactTest\Import-MailboxContacts.ps1:172 char:81

  23. Hi

    I am trying to run the script it gives me an error Parameter CSVFileName must be specified. I am new to powershell. I saved my contacts.csv file in the same directory where script is and run the script in Exchange powershell console.

    Do I need to give the path or name of CSV file in script some where ?

    Thanks
    Worbis

  24. Hi Steve,
    I was one of the unlucky ones who actually downloaded and installed SP1 RU3 recently. I know Microsoft pulled this patch due to the BES issues however, this script now no longer works correctly. I run exactly the same script, it appears to add all of the contacts, but when you go to the person’s contact folder, no contacts are showing up!

    I am not sure where to begin since the script “appears” to run just fine. I see the names being added and everything…but no contacts show up. I have tested this multiple ways so it’s not a the csv file or the mailbox. It’s like it places them into the mailbox hidden from view.

    Any ideas on how to fix it?

  25. Steve
    Thank you for this script, but I have one question. Not being a coder, how do I direct the script to save contacts in a sub-folder of the main contacts folder for a user?

  26. Steve,

    Thanks a ton for creating this script! With over 1000 users wanting their external contacts from their Apple address books upon migration to Exchange 2010 (OWA only), this is a real life saver.

    Since the EWS was updated to 1.1 (as Richard mentioned), just had to adjust the script to read 1.1 instead of 1.0 where you reference it. Additionally, I too could not get the script to run with the -domain flag, but as stated above, the workaround was to put the full upn in instead.

    Thanks again for your great work on this!
    -David

  27. Thank you for this script! It will be really useful to me. Here are some points I encountered getting it to work with Live@Edu, which I thought other readers might find useful.

    As the EWS API available for download now is version 1.1 rather than 1.0, if you install in the default path, you need to specify the EWS path to the script or amend the script.

    Live@Edu Outlook Live is Outlook 2010. (This is stated in other posts by Steve but not clear from this one alone)

    Autodiscovery of Live@Edu EWS did not work for me. I got an exception: “Autodiscover blocked a potentially insecure redirection to
    https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload.” To make it work I think it is necessary to pass a delegate that returns true, but I have not worked out how to define delegates in PowerShell. I avoided using autodiscovery by giving the EWS address: https://pod51007.outlook.com/EWS/Exchange.asmx. You can see your pod number from the URL when you view your mail.

    As bigvin found, if I specified the domain argument to the script, I got an exception:
    Exception calling “Bind” with “2″ argument(s): “The request failed. The remote server returned an error: (401) Unauthorized.”
    It worked to have no domain argument, but “@ourdomain.org.uk” at the end of the admin’s username.

    I also got this same 401 exception if I attempted to use a service account other than our original admin account, even if that account was assigned all the same admin roles, including ApplicationImpersonation. I would be very interested to know why this is.

    • Hi Richard,

      You’re right, EWS 1.1 RTM’ed in the meantime. I’ll update that. I’ve got a code snippet somewhere for that delegate so will dig it out and add it in..

      I’ll also spend a bit more time testing against outlook live and make the experience better. May take a few days tho.. Need a marathon blog update day I think!

      Steve

      • All that would be great. I will look out for the update.

        No need to rush though: the post is fabulously useful already. I hope your update day is the modern kind of marathon where people dress up in ridiculous costumes and not the original type where you drop dead at the end!

        Thanks again
        Richard

    • I too am experiencing difficulty with a 401 exception when attempting to run this script. Any assistance would be greatly appreciated.

  28. Pingback: How to export Email Headers from Exchange using Powershell | Steve Goodman's Tech Blog

  29. Steve, Thanks for your help. got alomost all of it working except I get the following error when the ps script is run
    Exception calling “Bind” with “2″ argument(s): “Request failed. The remote server returned an error: (401) Unauthorized
    .”

  30. Hey,
    the script work´s perfect for me but is there an solution to import the contact´s into a contact folder int he public store ?

    Thx

  31. no C# unfortunately, any other ideas? I just downloaded powergui to see if that can make it simple enough
    Appreciate any help

  32. I don’t suppose anyone could provide a web page for users to pass the appropriate variables into this script for ‘self service’
    ie: a browse button to the .csv file, username field, email address field password field etc.
    and have all of that passed to the powershell script so users can import their own contacts…

    Thanks for any help.

  33. In your example code, there doesn’t appear to be a way to deal with groups of contacts that the user may have created in the original address book. Would you happen to know the format of the attributes on the EWS side that would be used for group entries in a user’s contacts?

    • Hi Kurt,

      Nope, it doesn’t – is this something you would like? I can look at adding it if it will help you. I don’t know of the top of my head what would be needed to make it work but happy to find out.

      Steve

      • I wouldn’t worry too much about it, as we’re treating it as a “would be nice” kind-of thing, with just getting the contacts transferred being the main focus. If you happen to come up with something, that would be great.

        Thanks,
        Kurt

    • Great script! Thank you.
      One question: sometimes the new folder is automatically shared with a random person? While this is not true for the default settings? Do you have a clue?

        • Hi Steve, yes, a named person, but not always the same person. And with the other folders, there is no sharing.
          My solution is now to create the folder first and then update the permissions.

          $FolderPermission = new-object Microsoft.Exchange.WebServices.Data.FolderPermission([Microsoft.Exchange.WebServices.Data.StandardUser]::Default,[Microsoft.Exchange.WebServices.Data.FolderPermissionLevel]::None)
          $ContactsFolder.Permissions.Add($FolderPermission)
          $FolderPermission = new-object Microsoft.Exchange.WebServices.Data.FolderPermission([Microsoft.Exchange.WebServices.Data.StandardUser]::Anonymous,[Microsoft.Exchange.WebServices.Data.FolderPermissionLevel]::None)
          $ContactsFolder.Permissions.Add($FolderPermission)
          $ContactsFolder.Update()

  34. Pingback: Tweets that mention Using Powershell to import contacts into Exchange and Outlook Live « Steve Goodman's Tech Blog – The weblog of an IT pro specialising in Exchange, Exchange, VMware, Servers and Storage -- Topsy.com

Leave a Reply