Somebody asked last week about exporting contacts from Exchange via EWS to a CSV file and I realised I didn't have a basic sample for doing this. Contacts are one of the more richer exchange datatypes and can hold a lot of different information which you may or may not want to capture in a CSV export. In this sample script I'll show you how you can export data from the normal contact strongly typed properties like GivenName and Surname and the Indexed properties which are used to store the EmailAddresses, PhoneNumbers and Address details and also any extended properties like the Gender property which there are no strongly typed property for.
As I mentioned Contacts have a lot of properties so this script doesn't export everything just a subsection to show how to export properties from each of the different subgroups I talked about. To add other properties to script eg like the JobTitle you need to make the following modifications
Add the property to the Custom object
$expObj = "" | select DisplayName,GivenName,Surname,Gender,Email1DisplayName,Email1Type,Email1EmailAddress,BusinessPhone,MobilePhone,HomePhone,BusinessStreet,BusinessCity,BusinessState,HomeStreet,HomeCity,HomeState,JobTitle
Then set the property within the Item Iteration
$expObj.JobTitle = $item.JobTitle
I've put a download of this script here the code looks like
As I mentioned Contacts have a lot of properties so this script doesn't export everything just a subsection to show how to export properties from each of the different subgroups I talked about. To add other properties to script eg like the JobTitle you need to make the following modifications
Add the property to the Custom object
$expObj = "" | select DisplayName,GivenName,Surname,Gender,Email1DisplayName,Email1Type,Email1EmailAddress,BusinessPhone,MobilePhone,HomePhone,BusinessStreet,BusinessCity,BusinessState,HomeStreet,HomeCity,HomeState,JobTitle
Then set the property within the Item Iteration
$expObj.JobTitle = $item.JobTitle
I've put a download of this script here the code looks like
- ## Get the Mailbox to Access from the 1st commandline argument
- $MailboxName = $args[0]
- ## Load Managed API dll
- Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
- ## Set Exchange Version
- $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2
- ## Create Exchange Service Object
- $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)
- ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials
- #Credentials Option 1 using UPN for the windows Account
- $psCred = Get-Credential
- $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())
- $service.Credentials = $creds
- #Credentials Option 2
- #service.UseDefaultCredentials = $true
- ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates
- ## Code From http://poshcode.org/624
- ## Create a compilation environment
- $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
- $Compiler=$Provider.CreateCompiler()
- $Params=New-Object System.CodeDom.Compiler.CompilerParameters
- $Params.GenerateExecutable=$False
- $Params.GenerateInMemory=$True
- $Params.IncludeDebugInformation=$False
- $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null
- $TASource=@'
- namespace Local.ToolkitExtensions.Net.CertificatePolicy{
- public class TrustAll : System.Net.ICertificatePolicy {
- public TrustAll() {
- }
- public bool CheckValidationResult(System.Net.ServicePoint sp,
- System.Security.Cryptography.X509Certificates.X509Certificate cert,
- System.Net.WebRequest req, int problem) {
- return true;
- }
- }
- }
- '@
- $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
- $TAAssembly=$TAResults.CompiledAssembly
- ## We now create an instance of the TrustAll and attach it to the ServicePointManager
- $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
- [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
- ## end code from http://poshcode.org/624
- ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use
- #CAS URL Option 1 Autodiscover
- $service.AutodiscoverUrl($MailboxName,{$true})
- "Using CAS Server : " + $Service.url
- #CAS URL Option 2 Hardcoded
- #$uri=[system.URI] "https://casservername/ews/exchange.asmx"
- #$service.Url = $uri
- ## Optional section for Exchange Impersonation
- #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)
- $ExportCollection = @()
- Write-Host "Process Contacts"
- $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName)
- $Contacts = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
- $psPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
- $PR_Gender = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(14925,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Short)
- $psPropset.Add($PR_Gender)
- #Define ItemView to retrive just 1000 Items
- $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
- $fiItems = $null
- do{
- $fiItems = $service.FindItems($Contacts.Id,$ivItemView)
- [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)
- foreach($Item in $fiItems.Items){
- if($Item -is [Microsoft.Exchange.WebServices.Data.Contact]){
- $expObj = "" | select DisplayName,GivenName,Surname,Gender,Email1DisplayName,Email1Type,Email1EmailAddress,BusinessPhone,MobilePhone,HomePhone,BusinessStreet,BusinessCity,BusinessState,HomeStreet,HomeCity,HomeState
- $expObj.DisplayName = $Item.DisplayName
- $expObj.GivenName = $Item.GivenName
- $expObj.Surname = $Item.Surname
- $expObj.Gender = ""
- $Gender = $null
- if($item.TryGetProperty($PR_Gender,[ref]$Gender)){
- if($Gender -eq 2){
- $expObj.Gender = "Male"
- }
- if($Gender -eq 1){
- $expObj.Gender = "Female"
- }
- }
- $BusinessPhone = $null
- $MobilePhone = $null
- $HomePhone = $null
- if($Item.PhoneNumbers -ne $null){
- if($Item.PhoneNumbers.TryGetValue([Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone,[ref]$BusinessPhone)){
- $expObj.BusinessPhone = $BusinessPhone
- }
- if($Item.PhoneNumbers.TryGetValue([Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::MobilePhone,[ref]$MobilePhone)){
- $expObj.MobilePhone = $MobilePhone
- }
- if($Item.PhoneNumbers.TryGetValue([Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::HomePhone,[ref]$HomePhone)){
- $expObj.HomePhone = $HomePhone
- }
- }
- if($Item.EmailAddresses.Contains([Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1)){
- $expObj.Email1DisplayName = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Name
- $expObj.Email1Type = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].RoutingType
- $expObj.Email1EmailAddress = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Address
- }
- $HomeAddress = $null
- $BusinessAddress = $null
- if($item.PhysicalAddresses -ne $null){
- if($item.PhysicalAddresses.TryGetValue([Microsoft.Exchange.WebServices.Data.PhysicalAddressKey]::Home,[ref]$HomeAddress)){
- $expObj.HomeStreet = $HomeAddress.Street
- $expObj.HomeCity = $HomeAddress.City
- $expObj.HomeState = $HomeAddress.State
- }
- if($item.PhysicalAddresses.TryGetValue([Microsoft.Exchange.WebServices.Data.PhysicalAddressKey]::Business,[ref]$BusinessAddress)){
- $expObj.BusinessStreet = $BusinessAddress.Street
- $expObj.BusinessCity = $BusinessAddress.City
- $expObj.BusinessState = $BusinessAddress.State
- }
- }
- $ExportCollection += $expObj
- }
- }
- $ivItemView.Offset += $fiItems.Items.Count
- }while($fiItems.MoreAvailable -eq $true)
- $fnFileName = "c:\temp\" + $MailboxName + "-ContactsExport.csv"
- $ExportCollection | Export-Csv -NoTypeInformation -Path $fnFileName
- "Exported to " + $fnFileName