Importing and Synchronizing Contacts from a CSV (Outlook Express Export) into Exchange 2007 (private Contacts Folder or Public Contacts Folder) using
Following on from last week I’m going to put the Sync function I created into use and also show you how to create a contact in Powershell with a few lines of code using some wrappered EWS code I’ve put into my EWSUtil powershell library. I’ve also include some code to create a grouped list of contacst flagged with a custom property to allow full sync eg create if don’t exist create , delete if deleted from the syncfile and do property level changes if phone, address of name information is modified. I’ve used a csv file generated by doing an export in Outlook Express but this could be any csv file from any source.
Before we can use this process we need to set the target folder to where the contacts will be imported to or where the contacts we are going to sync with are located. For a local users contact folder something like this is needed.
$lcLocalContactFolderid = new-object EWSUtil.EWS.DistinguishedFolderIdType$lcLocalContactFolderid.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::contacts
$mbMailbox = new-object EWSUtil.EWS.EmailAddressType
$mbMailbox.EmailAddress = “user@domain.com”
$dTypeFld.Mailbox = $mbMailbox$lcLocalContacts = $ewc.getfolder($lcLocalContactFolderid)
$mbMailbox = new-object EWSUtil.EWS.EmailAddressType
$mbMailbox.EmailAddress = “user@domain.com”
$dTypeFld.Mailbox = $mbMailbox$lcLocalContacts = $ewc.getfolder($lcLocalContactFolderid)
If you want to target a Public folder it’s not just as easy as putting in the path to the folder we need to get the code to traverse that folder path and find the target folder. The method I use is to input a normal folder path the split this into an array and then starting at the root use a separate find folder on each parent folder in the dimensioning hierarchy this is a little hard to explain but the code explains it better.
$pfPublicFolderPath = "/PubContacts/SyncContacts"
$parentFolder = new-object EWSUtil.EWS.DistinguishedFolderIdType
$parentFolder.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::publicfoldersroot
$fldarry = new-object EWSUtil.EWS.BaseFolderIdType[] 1
$fldarry[0] = $parentFolder
$rfRootFolder = $ewc.getFolder($fldarry)
$pfArray = $pfPublicFolderPath.Split("/")
$cfContactsFolder = $rfRootFolder[0]
for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
$cfContactsFolder = $ewc.FindSubFolder($cfContactsFolder, $pfArray[$lint]);
}
$parentFolder = new-object EWSUtil.EWS.DistinguishedFolderIdType
$parentFolder.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::publicfoldersroot
$fldarry = new-object EWSUtil.EWS.BaseFolderIdType[] 1
$fldarry[0] = $parentFolder
$rfRootFolder = $ewc.getFolder($fldarry)
$pfArray = $pfPublicFolderPath.Split("/")
$cfContactsFolder = $rfRootFolder[0]
for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
$cfContactsFolder = $ewc.FindSubFolder($cfContactsFolder, $pfArray[$lint]);
}
Once we have our target folder we can do a number of things before going into synchronization I want to show some easy code for creating contacts using EWS from Powershell. To create a contact we really only need a csv file with 2 columns one for the name and one for the emailAddress eg
Name,EmailAddress
Fred FlintStone,Fred@slate.com
Barney Rubble,barney@slate.com
Fred FlintStone,Fred@slate.com
Barney Rubble,barney@slate.com
If you have a csv file that you want to import into a local users contacts folder first we need to create an Exchange Web Services Connection so we can use EWS and get the target folder as I’ve talked about above. Once this is done you can then read the csv file using the Import-csv powershell cmdlet. We then loop through each line of the csv file and create contacts from the information within. When creating a contact there are several properties you do need to set such as some Extended mapi properties that aren’t included in the EWS contactType class. These represent the displayName for emailaddress's also you need to make sure you set the FileAs and Subject properties so the contact will display correctly in Outlook and the address book. So the simplest code to create contacts from a 2 column csv file would look like (I’ve omitted the connect and folder find functions which I’ll include in the download im also splitting the name into to an array to fill in the firstname and surname properties).
import-csv $fnFileName | foreach-object{
$newcontact = new-object EWSUtil.EWS.ContactItemType
$namearray = $_.Name.split(" ")
$newcontact.GivenName = $namearray[0]
$newcontact.Surname = $namearray[1]
$newcontact.Subject = $_.Name
$newcontact.FileAs = $_.Name
$newcontact.DisplayName = $_.Name
$newcontact.EmailAddresses = new-object EWSUtil.EWS.EmailAddressDictionaryEntryType[] 1
$newcontact.EmailAddresses[0] = new-object EWSUtil.EWS.EmailAddressDictionaryEntryType
$newcontact.EmailAddresses[0].Key = [EWSUtil.EWS.EmailAddressKeyType]::EmailAddress1
$newcontact.EmailAddresses[0].Value = $_.EmailAddress
$dnEmailDisplayName1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$dnEmailDisplayName1.DistinguishedPropertySetIdSpecified = $true
$dnEmailDisplayName1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$dnEmailDisplayName1.PropertyId = 32896
$dnEmailDisplayName1.PropertyIdSpecified = $true
$dnEmailDisplayName1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String
$daEmailDisplayName1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$daEmailDisplayName1.DistinguishedPropertySetIdSpecified = $true
$daEmailDisplayName1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$daEmailDisplayName1.PropertyId = 32900
$daEmailDisplayName1.PropertyIdSpecified = $true;
$daEmailDisplayName1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String
$atEmailAddressType1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$atEmailAddressType1.DistinguishedPropertySetIdSpecified = $true
$atEmailAddressType1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$atEmailAddressType1.PropertyId = 32898
$atEmailAddressType1.PropertyIdSpecified = $true;
$atEmailAddressType1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String
$newcontact.ExtendedProperty = new-object EWSUtil.EWS.ExtendedPropertyType[] 3
$newcontact.ExtendedProperty[0] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[0].ExtendedFieldURI = $dnEmailDisplayName1
$newcontact.ExtendedProperty[0].Item = $_.Name + " (" + $_.EmailAddress + ")"
$newcontact.ExtendedProperty[1] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[1].ExtendedFieldURI = $daEmailDisplayName1
$newcontact.ExtendedProperty[1].Item = $_.EmailAddress
$newcontact.ExtendedProperty[2] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[2].ExtendedFieldURI = $atEmailAddressType1
$newcontact.ExtendedProperty[2].Item = "SMTP"
$_.EmailAddress
$ewc.AddNewContact($newcontact,$lcLocalContacts[0].FolderId)
}
$newcontact = new-object EWSUtil.EWS.ContactItemType
$namearray = $_.Name.split(" ")
$newcontact.GivenName = $namearray[0]
$newcontact.Surname = $namearray[1]
$newcontact.Subject = $_.Name
$newcontact.FileAs = $_.Name
$newcontact.DisplayName = $_.Name
$newcontact.EmailAddresses = new-object EWSUtil.EWS.EmailAddressDictionaryEntryType[] 1
$newcontact.EmailAddresses[0] = new-object EWSUtil.EWS.EmailAddressDictionaryEntryType
$newcontact.EmailAddresses[0].Key = [EWSUtil.EWS.EmailAddressKeyType]::EmailAddress1
$newcontact.EmailAddresses[0].Value = $_.EmailAddress
$dnEmailDisplayName1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$dnEmailDisplayName1.DistinguishedPropertySetIdSpecified = $true
$dnEmailDisplayName1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$dnEmailDisplayName1.PropertyId = 32896
$dnEmailDisplayName1.PropertyIdSpecified = $true
$dnEmailDisplayName1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String
$daEmailDisplayName1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$daEmailDisplayName1.DistinguishedPropertySetIdSpecified = $true
$daEmailDisplayName1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$daEmailDisplayName1.PropertyId = 32900
$daEmailDisplayName1.PropertyIdSpecified = $true;
$daEmailDisplayName1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String
$atEmailAddressType1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$atEmailAddressType1.DistinguishedPropertySetIdSpecified = $true
$atEmailAddressType1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$atEmailAddressType1.PropertyId = 32898
$atEmailAddressType1.PropertyIdSpecified = $true;
$atEmailAddressType1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String
$newcontact.ExtendedProperty = new-object EWSUtil.EWS.ExtendedPropertyType[] 3
$newcontact.ExtendedProperty[0] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[0].ExtendedFieldURI = $dnEmailDisplayName1
$newcontact.ExtendedProperty[0].Item = $_.Name + " (" + $_.EmailAddress + ")"
$newcontact.ExtendedProperty[1] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[1].ExtendedFieldURI = $daEmailDisplayName1
$newcontact.ExtendedProperty[1].Item = $_.EmailAddress
$newcontact.ExtendedProperty[2] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[2].ExtendedFieldURI = $atEmailAddressType1
$newcontact.ExtendedProperty[2].Item = "SMTP"
$_.EmailAddress
$ewc.AddNewContact($newcontact,$lcLocalContacts[0].FolderId)
}
Okay now we can create contacts syncronizing is just matter of using the same logic and adding some code that before creating the contacts checks to see if it exists and if it does then does a property level check of the contact and then updates any information that has changed or does nothing at all. To facilite this i've made a few changes to the code above first i've added a custom Mapi property to mark any contacts that are created with this process. then when it comes time to syncronise i have a function that first finds all the contacts that this process has created when (or if) it had run before. This function returns a Hashtable indexed by the Email address so it makes it easy to check if the contact has already been created and determines if the sync needs to be run for changed properties. On the back side contacts can also be deleted if they no longer exist in the file
So the Full sync,add,delete logic would look like
$_."E-mail Address"
if ($contactsHash.containskey($_."E-mail Address")){
"Address Exist Test Sync"
$dsContact = $contactsHash[$_."E-mail Address"]
$diffs = $ewc.DiffConact($newcontact,$dsContact)
if ($diffs.Count -ne 0){
"Number Changes Found " + $diffs.Count
[VOID]$ewc.UpdateContact($diffs,$dsContact.ItemId)
}
}else{
"CreateContact"
$ewc.AddNewContact($newcontact,$cfContactsFolder.FolderId )
}
}
$diDelCollection = @()
$delitems = $false
foreach ($key in $contactsHash.Keys){
if ($fileContactsHash.ContainsKey($key) -eq $false){
$diDelCollection += $contactsHash[$key]
$delitems = $true
}
}
if ($delitems -eq $true){
$delbis = new-object EWSUtil.EWS.BaseItemIdType[] $diDelCollection.length
for($delint=0;$delint -lt [Int]$diDelCollection.length;$delint++){
$diDelCollection[$delint].Subject.ToString()
$delbis[$delint] = $diDelCollection[$delint].ItemId}
$delbis
$ewc.DeleteItems($delbis,[EWSUtil.EWS.DisposalType]::SoftDelete)
"Items Deleted"
}
if ($contactsHash.containskey($_."E-mail Address")){
"Address Exist Test Sync"
$dsContact = $contactsHash[$_."E-mail Address"]
$diffs = $ewc.DiffConact($newcontact,$dsContact)
if ($diffs.Count -ne 0){
"Number Changes Found " + $diffs.Count
[VOID]$ewc.UpdateContact($diffs,$dsContact.ItemId)
}
}else{
"CreateContact"
$ewc.AddNewContact($newcontact,$cfContactsFolder.FolderId )
}
}
$diDelCollection = @()
$delitems = $false
foreach ($key in $contactsHash.Keys){
if ($fileContactsHash.ContainsKey($key) -eq $false){
$diDelCollection += $contactsHash[$key]
$delitems = $true
}
}
if ($delitems -eq $true){
$delbis = new-object EWSUtil.EWS.BaseItemIdType[] $diDelCollection.length
for($delint=0;$delint -lt [Int]$diDelCollection.length;$delint++){
$diDelCollection[$delint].Subject.ToString()
$delbis[$delint] = $diDelCollection[$delint].ItemId}
$delbis
$ewc.DeleteItems($delbis,[EWSUtil.EWS.DisposalType]::SoftDelete)
"Items Deleted"
}
In the download i've create a sample that uses an Outlook Express Address Book csv Export with all the fields ticked that imports and syncronzes with a public Contacts folders as well as the Local contacts import sample I've talked about. I've put the download here. To use these scrripts you need to use the latest EWSUtil Powershell library which you can download from https://github.com/gscales/Powershell-Scripts/raw/master/ScriptArchive/.
For more information on using the library and connection and authentication options this is documented in another post