by

Exporting Contacts to a CSV file utilizing the EWS Managed API and Powershell

Exporting Contacts to a CSV file utilizing the EWS Managed API and Powershell Someone requested final week about exporting contacts from Alternate through EWS to a CSV file and I realised I did not have a fundamental pattern for doing this. Contacts are one of many extra richer trade datatypes and may maintain a number of completely different info which you will or might not wish to seize in a CSV export. On this pattern script I am going to present you how one can export knowledge from the traditional contact strongly typed properties like GivenName and Surname and the Listed properties that are used to retailer the EmailAddresses, PhoneNumbers and Handle particulars and likewise any prolonged properties just like the Gender property which there aren’t any strongly typed property for.

As I discussed Contacts have a number of properties so this script does not export all the things only a subsection to point out the right way to export properties from every of the completely different subgroups I talked about. So as to add different properties to script eg  just like the JobTitle it is advisable to make the next modifications

Add the property to the Customized object

$expObj = “” | choose DisplayName,GivenName,Surname,Gender,Email1DisplayName,Email1Type,Email1EmailAddress,BusinessPhone,MobilePhone,HomePhone,BusinessStreet,BusinessCity,BusinessState,HomeStreet,HomeCity,HomeState,JobTitle

Then set the property throughout the Merchandise Iteration

$expObj.JobTitle  = $merchandise.JobTitle

I’ve put a download of this script right here the code appears to be like like

  1. ## Get the Mailbox to Entry from the 1st commandline argument  
  2.   
  3. $MailboxName = $args[0]  
  4.   
  5. ## Load Managed API dll    
  6. Add-Kind -Path “C:Program FilesMicrosoftExchangeWeb Services2.0Microsoft.Exchange.WebServices.dll”    
  7.     
  8. ## Set Alternate Model    
  9. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Alternate2010_SP2  
  10.     
  11. ## Create Alternate Service Object    
  12. $service = New-Object Microsoft.Alternate.WebServices.Knowledge.ExchangeService($ExchangeVersion)    
  13.     
  14. ## Set Credentials to use two choices are availible Option1 to use explict credentials or Possibility 2 use the Default (logged On) credentials    
  15.     
  16. #Credentials Possibility 1 utilizing UPN for the home windows Account    
  17. $psCred = Get-Credential    
  18. $creds = New-Object System.Internet.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  19. $service.Credentials = $creds        
  20.     
  21. #Credentials Possibility 2    
  22. #service.UseDefaultCredentials = $true    
  23.     
  24. ## Select to ignore any SSL Warning points precipitated by Self Signed Certificates    
  25.     
  26. ## Code From http://poshcode.org/624  
  27. ## Create a compilation setting  
  28. $Supplier=New-Object Microsoft.CSharp.CSharpCodeProvider  
  29. $Compiler=$Supplier.CreateCompiler()  
  30. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  31. $Params.GenerateExecutable=$False  
  32. $Params.GenerateInMemory=$True  
  33. $Params.IncludeDebugInformation=$False  
  34. $Params.ReferencedAssemblies.Add(“System.DLL”) | Out-Null  
  35.   
  36. $TASource=@ 
  37.   namespace Native.ToolkitExtensions.Internet.CertificatePolicy{ 
  38.     public class TrustAll : System.Internet.ICertificatePolicy { 
  39.       public TrustAll() {  
  40.       } 
  41.       public bool CheckValidationResult(System.Internet.ServicePoint sp, 
  42.         System.Safety.Cryptography.X509Certificates.X509Certificates cert,  
  43.         System.Internet.WebRequest req, int downside) { 
  44.         return true; 
  45.       } 
  46.     } 
  47.   } 
  48. @   
  49. $TAResults=$Supplier.CompileAssemblyFromSource($Params,$TASource)  
  50. $TAAssembly=$TAResults.CompiledAssembly  
  51.   
  52. ## We now create an occasion of the TrustAll and connect it to the ServicePointManager  
  53. $TrustAll=$TAAssembly.CreateInstance(“Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll”)  
  54. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  55.   
  56. ## finish code from http://poshcode.org/624  
  57.     
  58. ## Set the URL of the CAS (Consumer Entry Server) to use two choices are availbe to use Autodiscover to discover the CAS URL or Hardcode the CAS to use    
  59.     
  60. #CAS URL Possibility 1 Autodiscover    
  61. $service.AutodiscoverUrl($MailboxName,{$true})    
  62. “Using CAS Server : “ + $Service.url     
  63.      
  64. #CAS URL Possibility 2 Hardcoded    
  65.     
  66. #$uri=[system.URI] “https://casservername/ews/exchange.asmx”    
  67. #$service.Url = $uri      
  68.     
  69. ## Non-compulsory part for Alternate Impersonation    
  70.     
  71. #$service.ImpersonatedUserId = new-object Microsoft.Alternate.WebServices.Knowledge.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  72. $ExportCollection = @()  
  73. Write-Host “Process Contacts”  
  74. $folderid= new-object Microsoft.Alternate.WebServices.Knowledge.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName)     
  75. $Contacts = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  76.   
  77. $psPropset = new-object Microsoft.Alternate.WebServices.Knowledge.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)   
  78. $PR_Gender = New-Object Microsoft.Alternate.WebServices.Knowledge.ExtendedPropertyDefinition(14925,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Quick)  
  79. $psPropset.Add($PR_Gender)  
  80.    
  81. #Outline ItemView to retrive simply 1000 Objects      
  82. $ivItemView =  New-Object Microsoft.Alternate.WebServices.Knowledge.ItemView(1000)      
  83. $fiItems = $null      
  84. do{      
  85.     $fiItems = $service.FindItems($Contacts.Id,$ivItemView)   
  86.     [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  87.     foreach($Merchandise in $fiItems.Objects){       
  88.         if($Merchandise -is [Microsoft.Exchange.WebServices.Data.Contact]){  
  89.             $expObj = “” | choose DisplayName,GivenName,Surname,Gender,Email1DisplayName,Email1Type,Email1EmailAddress,BusinessPhone,MobilePhone,HomePhone,BusinessStreet,BusinessCity,BusinessState,HomeStreet,HomeCity,HomeState  
  90.             $expObj.DisplayName = $Merchandise.DisplayName  
  91.             $expObj.GivenName = $Merchandise.GivenName  
  92.             $expObj.Surname = $Merchandise.Surname  
  93.             $expObj.Gender = “”  
  94.             $Gender = $null  
  95.             if($merchandise.TryGetProperty($PR_Gender,[ref]$Gender)){  
  96.                 if($Gender -eq 2){  
  97.                     $expObj.Gender = “Male”   
  98.                 }  
  99.                 if($Gender -eq 1){  
  100.                     $expObj.Gender = “Female”   
  101.                 }  
  102.             }  
  103.             $BusinessPhone = $null  
  104.             $MobilePhone = $null  
  105.             $HomePhone = $null  
  106.             if($Merchandise.PhoneNumbers -ne $null){  
  107.                 if($Merchandise.PhoneNumbers.TryGetValue([Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone,[ref]$BusinessPhone)){  
  108.                     $expObj.BusinessPhone = $BusinessPhone  
  109.                 }  
  110.                 if($Merchandise.PhoneNumbers.TryGetValue([Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::MobilePhone,[ref]$MobilePhone)){  
  111.                     $expObj.MobilePhone = $MobilePhone  
  112.                 }     
  113.                 if($Merchandise.PhoneNumbers.TryGetValue([Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::HomePhone,[ref]$HomePhone)){  
  114.                     $expObj.HomePhone = $HomePhone  
  115.                 }     
  116.             }             
  117.             if($Merchandise.EmailAddresses.Accommodates([Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1)){                  
  118.                 $expObj.Email1DisplayName = $Merchandise.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Identify  
  119.                 $expObj.Email1Type = $Merchandise.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].RoutingType  
  120.                 $expObj.Email1EmailAddress = $Merchandise.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Handle  
  121.             }  
  122.             $HomeAddress = $null  
  123.             $BusinessAddress = $null  
  124.             if($merchandise.PhysicalAddresses -ne $null){  
  125.                 if($merchandise.PhysicalAddresses.TryGetValue([Microsoft.Exchange.WebServices.Data.PhysicalAddressKey]::House,[ref]$HomeAddress)){  
  126.                     $expObj.HomeStreet = $HomeAddress.Avenue  
  127.                     $expObj.HomeCity = $HomeAddress.Metropolis  
  128.                     $expObj.HomeState = $HomeAddress.State  
  129.                 }  
  130.                 if($merchandise.PhysicalAddresses.TryGetValue([Microsoft.Exchange.WebServices.Data.PhysicalAddressKey]::Enterprise,[ref]$BusinessAddress)){  
  131.                     $expObj.BusinessStreet = $BusinessAddress.Avenue  
  132.                     $expObj.BusinessCity = $BusinessAddress.Metropolis  
  133.                     $expObj.BusinessState = $BusinessAddress.State  
  134.                 }  
  135.             }  
  136.               
  137.             $ExportCollection += $expObj  
  138.         }  
  139.     }      
  140.     $ivItemView.Offset += $fiItems.Objects.Rely      
  141. }whereas($fiItems.MoreAvailable -eq $true)   
  142.   
  143. $fnFileName = “c:temp” + $MailboxName + “-ContactsExport.csv 
  144. $ExportCollection | Export-Csv -NoTypeInformation -Path $fnFileName 
  145. Exported to ” + $fnFileName