Skip to main content

Flexible Exchange Contact creation script using Powershell import-csv and the EWS Managed API

Contacts can be a constant source or pain and target for automation within any Exchange environment because of our ever growing propensity to move, create ,import and export mailboxes as well as the ever growing list of mobile, tablet devices, social network sites and software that creates and distributes contacts in a wide variety of formats. If you have ever scripted contacts in Exchange because of the amount of properties and different formats of these properties you may have realized that writing a flexible reusable script can be challenge. These scripts tend to become long and messy which make them harder to reuse in varying situations. So my goal was to write something that first I could use easily to import contacts from a CSV file but also down the track tackle some Vcard import code I need to port across.

With Exchange contacts you have 5 distinct property groups you need to deal with in EWS

Normal (things like FirstName, LastName etc)
Phone (Mobile, Home Business etc)
Address (Home, Business, Other)
Email (3 different)
Extended Properties – (Any Mapi properties that aren’t provided by strongly-typed contact in EWS)

Each of these properties need to be set in their own unique way so to make using contacts easier I wanted a script that would essentially flatten out the process. Eg one method that can be used to set any property no matter how few or how many of the actual contact properties that I wanted to set. What I came up with to cater for this was first a instead of setting properties directly on the strongly-typed object I’ve used a Hashtable to store a custom object to act as an intermediary. This then allowed me to create a simple function to allow for setting each property

function SetProp([String]$Type,[Object]$Name,[Object]$Value){
$p1Prop1 = "" | select proptype,name,value
$p1Prop1.proptype = $Type
$p1Prop1.name = $Name
$p1Prop1.value = $Value
$ContactProps.Add($Name,$p1Prop1)
}

So the property Type would be one of the five types I’ve listed above the name would be the name of the property (or for the more complex name the name of the dictionary property and the actually property separated with a (.).)
This means when I want to set a normal property like first name I can use

SetProp "Normal" "GivenName" “Contacts First Name”

If I want to set the first Email address I would use

SetProp "Email" "EmailAddress1.Address" “User@emailaddress.com”

To set the Home address properties of a contact you need

SetProp "Address" "Home.City" "Blah Blah"
SetProp "Address" "Home.State" "NSW"
SetProp "Address" "Home.Street" "19 Blah Ave"
SetProp "Address" "Home.PostalCode" "2153"

For Extended properties it does require more the one line because the property does need to be defined for example to set the Pr_Gender property use

$gender = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(14925,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Short)
SetProp "Extended" $gender 2

Once all the properties are set you then call the CreateContact function which will then enumerate back through the Hashtable and has some logic that should then deal with the messiness of setting the actual strongly type object properties within a minimal amount of code.

Putting it to use

I built this script to do some hard work so the first task I had was create a bunch of different contacts within different public folders from different CSV files. The CSV file was pretty simple it had firstName , LastName, Company , EmailAddress . Powershell has a create CSV cmdlet called import-csv that make working with text file really easy so this solved that part easy. To create contact in a public folder I first need to find the EWSid of the folder in question. Fortunately I already had the code from another script. The finally script that did the Public Folder import from a CSV looked like the following. I've put a downlaod with a few different version of this here.

The script itself looks like.

### Contact Property List
###
### Normal : to Set eg SetProp "Normal" "GivenName" "MyfirstName"
### http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.contact_members%28v=EXCHG.80%29.aspx
###
### Email : to Set eg SetProp "Email" "EmailAddress1.Address" "glenscales@yahoo.com"
### EmailAddress1.Address
### EmailAddress2.Address
### EmailAddress3.Address
### EmailAddress1.Name
### EmailAddress2.Name
### EmailAddress3.Name
###
### Phone : to Set eg SetProp SetProp "Phone" "MobilePhone" "2345234523"
### AssistantPhone The assistant's phone number.
### BusinessFax The business fax number.
### BusinessPhone The business phone number.
### BusinessPhone2 The second business phone number.
### Callback The callback number.
### CarPhone The car phone number.
### CompanyMainPhone The company's main phone number.
### HomeFax The home fax number.
### HomePhone The home phone number.
### HomePhone2 The second home phone number.
### Isdn The ISDN number.
### MobilePhone The mobile phone number.
### OtherFax An alternate fax number.
### OtherTelephone An alternate phone number.
### Pager The pager number.
### PrimaryPhone The primary phone number.
### RadioPhone The radio phone number.
### Telex The Telex number.
### TtyTddPhone The TTY/TTD phone number.
###
### Address : to Set eg SetProp SetProp "Address" "Business.City" "Sydney"
###
### Business.City
### Business.CountryOrRegion
### Business.PostalCode
### Business.State
### Business.Street
###
### Home.City
### Home.CountryOrRegion
### Home.PostalCode
### Home.State
### Home.Street
###
### Other.City
### Other.CountryOrRegion
### Other.PostalCode
### Other.State
### Other.Street
###
### Extended : to Set
###
### $AddressGuid = new-object Guid("00062004-0000-0000-C000-000000000046")
###
### $email1DisplayNameProp = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition($AddressGuid,32896, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)
### SetProp "Extended" $email1DisplayNameProp "Fredoo"
###
### $gender = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(14925,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Short)
### SetProp "Extended" $gender 2
###

$MailboxName = "user@domain.com"
$csvFile = "c:\allcustm.csv"

$AddressGuid = new-object Guid("00062004-0000-0000-C000-000000000046")
$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)

function SetProp([String]$Type,[Object]$Name,[Object]$Value){
$p1Prop1 = "" | select proptype,name,value
$p1Prop1.proptype = $Type
$p1Prop1.name = $Name
$p1Prop1.value = $Value
$ContactProps.Add($Name,$p1Prop1)
}

Function FindTargetFolder([String]$FolderPath){
$tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)
$pfArray = $FolderPath.Split("/")
for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
$pfArray[$lint]
$fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$pfArray[$lint])
$findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)
if ($findFolderResults.TotalCount -gt 0){
foreach($folder in $findFolderResults.Folders){
$tfTargetFolder = $folder
}
}
else{
"Error Folder Not Found"
$tfTargetFolder = $null
break
}
}
$Global:findFolder = $tfTargetFolder
}

function CreateContact($service,$ContactProps,$Folder){

$NewContact = new-object Microsoft.Exchange.WebServices.Data.Contact($service)

$ContactProps.GetEnumerator() | foreach-object {
$propName = $_.Value.name
$propValue = $_.Value.value
if ($_.Value.proptype -ne "Extended"){
$psplit = $propName.split(".")
$pval1 = $psplit[0]
$pval2 = $psplit[1]
}
Switch($_.Value.proptype){
"Normal" {$NewContact.$propName = $propValue}
"Email" {
if ($NewContact.EmailAddresses.Contains([Microsoft.Exchange.WebServices.Data.EmailAddressKey]::$pval1)){
$EmailEntry = $NewContact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::$pval1]
}
else{
$EmailEntry = new-object Microsoft.Exchange.WebServices.Data.EmailAddress
}
$EmailEntry.$pval2 = $propValue
$NewContact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::$pval1] = $EmailEntry
}
"Phone" {
$NewContact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::$propName] = $propValue
}
"Address"{
if ($NewContact.PhysicalAddresses.Contains([Microsoft.Exchange.WebServices.Data.PhysicalAddressKey]::$pval1)){
$PhysicalAddressEntry = $NewContact.PhysicalAddresses[[Microsoft.Exchange.WebServices.Data.PhysicalAddressKey]::$pval1]
}
else{
$PhysicalAddressEntry = new-object Microsoft.Exchange.WebServices.Data.PhysicalAddressEntry
}
$PhysicalAddressEntry.$pval2 = $propValue
$NewContact.PhysicalAddresses[[Microsoft.Exchange.WebServices.Data.PhysicalAddressKey]::$pval1] = $PhysicalAddressEntry
}
"Extended" {
$NewContact.SetExtendedProperty($propName,$propValue)
}


}
}
$NewContact.Save($Global:findFolder.Id)
"Contact Created : " + $NewContact.FileAs
$Global:newContact = $NewContact
}


$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($aceuser.mail.ToString())


$folderid = FindTargetFolder ("/folder1/folder2")

$ContactProps = @{ }


import-csv $csvFile | foreach-object {
$ContactProps.Clear()
SetProp "Normal" "GivenName" $_.FirstName
SetProp "Normal" "Surname" $_.LastName
$fileasName = $_.FirstName + "," + $_.LastName
SetProp "Normal" "Subject" $fileasName
SetProp "Normal" "FileAs" $fileasName
SetProp "Normal" "CompanyName" $_.Company
SetProp "Email" "EmailAddress1.Address" $_.Email
CreateContact $service $ContactProps

}

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

How to access and restore deleted Items (Recoverable Items) in the Exchange Online Mailbox dumpster with the Microsoft Graph API and PowerShell

As the information on how to do this would cover multiple posts, I've bound this into a series of mini post docs in my GitHub Repo to try and make this subject a little easier to understand and hopefully navigate for most people.   The Binder index is  https://gscales.github.io/Graph-Powershell-101-Binder/   The topics covered are How you can access the Recoverable Items Folders (and get the size of these folders)  How you can access and search for items in the Deletions and Purges Folders and also how you can Export an item to an Eml from that folder How you can Restore a Deleted Item back to the folder it was deleted from (using the Last Active Parent FolderId) and the sample script is located  https://github.com/gscales/Powershell-Scripts/blob/master/Graph101/Dumpster.ps1

Using the MSAL (Microsoft Authentication Library) in EWS with Office365

Last July Microsoft announced here they would be disabling basic authentication in EWS on October 13 2020 which is now a little over a year away. Given the amount of time that has passed since the announcement any line of business applications or third party applications that you use that had been using Basic authentication should have been modified or upgraded to support using oAuth. If this isn't the case the time to take action is now. When you need to migrate a .NET app or script you have using EWS and basic Authentication you have two Authentication libraries you can choose from ADAL - Azure AD Authentication Library (uses the v1 Azure AD Endpoint) MSAL - Microsoft Authentication Library (uses the v2 Microsoft Identity Platform Endpoint) the most common library you will come across in use is the ADAL libraries because its been around the longest, has good support across a number of languages and allows complex authentications scenarios with support for SAML etc. The
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.