by

Export the GAL or Deal with checklist with EWS to Vcards in 2013 MEC pattern 1

Export the GAL or Deal with checklist with EWS to Vcards in 2013 MEC pattern 1 That is the primary of the pattern scripts I included in my MEC speak final Monday.  This script makes use of three of the brand new operations in EWS in Alternate 2013 to export all of the deal with checklist entries of a specific Addresslist to particular person Vcards (together with the person picture) utilizing simply EWS. None of those operations are included within the EWS Managed API, so to make use of these operations I am utilizing some Uncooked SOAP and posting the EWS request utilizing the usual httpwebrequest class in .Internet and processing the response in XML.

The FindPeople Operation is used firstly to web page by way of all of the entries in an Deal with checklist in teams of 100 entries at a time. To make use of this operation you first have to get the GUID for the deal with checklist you wish to export and arduous code this within the $ABGUID variable eg.

$ABGUID = “6c118670-2f72-4213-944c-ab1e97d63f9b”;

To get the GUID on your International Deal with Checklist you’ll want to use the Get-GlobalAddressList Cmdlet http://technet.microsoft.com/en-us/library/aa996579%28v=exchg.150%29.aspx or if you wish to export one of many different Deal with lists you should utilize the Get-AddressList cmdlet http://technet.microsoft.com/en-us/library/aa996782(v=exchg.150).aspx .

eg

To make use of these cmdlet’s in Workplace365 you’ll want to be sure you are assigned the Deal with Lists Function in RBAC

eg run

New-ManagementRoleAssignment -Function ‘Deal with Lists’ -Person username
The FindPeople operation returns the PersonaId for every of the AddressList entries so the subsequent a part of the script makes use of the GetPersona Operation to get all of the Deal with checklist entries particulars. Personas are a distinct means of representing contact knowledge that is outlined in http://msdn.microsoft.com/en-us/library/workplace/jj190895(v=exchg.150).aspx . This specific script simply makes use of this operation to seize the contact particulars saved in Energetic Listing (or Azure AD) for the actual persona (or Deal with checklist Entry in query). At present I have never labored out a solution to batch this operation in EWS (if anybody is aware of please ping me) so its executing one OP per entry(which is sort of gradual).
The final operation the script makes use of is the GerUserPhoto operation which is only a REST endpoint so it is good and simple to make use of. It returns a ByteArray which then will get transformed to a Base64 string with LineBreaks so its correctly formatted within the VCard file.
To run this script you’ll want to go it in a Mailbox to run as and as I discussed earlier than you’ll want to hardcode the GUID of the AddressList you wish to export. Whereas not one of the operations used to do the export are within the Managed API, I’ve included within the often Managed API Autodiscovery routines.  You can even set the placement of the export listing in 
$exportFolder = “c:temp”
I’ve put a download of this script right here the code itself appears to be like like

  1. ## Get the Mailbox to Entry from the 1st commandline argument  
  2.   
  3. $MailboxName = $args[0]  
  4. $exportFolder = “c:temp” 
  5.  
  6. $ABGUID = “6c118670-2f72-4213-944c-ab1e97d63f9b“; 
  7.  
  8. ## Load Managed API dll   
  9. Add-Kind -Path “C:Program FilesMicrosoftExchangeWeb Services2.0Microsoft.Alternate.WebServices.dll”   
  10.    
  11. ## Set Alternate Model   
  12. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Alternate2010_SP2   
  13.    
  14. ## Create Alternate Service Object   
  15. $service = New-Object Microsoft.Alternate.WebServices.Knowledge.ExchangeService($ExchangeVersion)   
  16.    
  17. ## Set Credentials to use two choices are availible Option1 to use explict credentials or Possibility 2 use the Default (logged On) credentials   
  18.    
  19. #Credentials Possibility 1 utilizing UPN for the home windows Account   
  20. $psCred = Get-Credential   
  21. $creds = New-Object System.Internet.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())   
  22. $service.Credentials = $creds       
  23.    
  24. #Credentials Possibility 2   
  25. #service.UseDefaultCredentials = $true   
  26.    
  27. ## Select to ignore any SSL Warning points brought about by Self Signed Certificates   
  28.    
  29. ## Code From http://poshcode.org/624 
  30. ## Create a compilation surroundings 
  31. $Supplier=New-Object Microsoft.CSharp.CSharpCodeProvider 
  32. $Compiler=$Supplier.CreateCompiler() 
  33. $Params=New-Object System.CodeDom.Compiler.CompilerParameters 
  34. $Params.GenerateExecutable=$False 
  35. $Params.GenerateInMemory=$True 
  36. $Params.IncludeDebugInformation=$False 
  37. $Params.ReferencedAssemblies.Add(“System.DLL“) | Out-Null 
  38.  
  39. $TASource=@’ 
  40.   namespace Native.ToolkitExtensions.Internet.CertificatePolicy{ 
  41.     public class TrustAll : System.Internet.ICertificatePolicy { 
  42.       public TrustAll() {  
  43.       } 
  44.       public bool CheckValidationResult(System.Internet.ServicePoint sp, 
  45.         System.Safety.Cryptography.X509Certificates.X509Certificates cert,  
  46.         System.Internet.WebRequest req, int downside) { 
  47.         return true; 
  48.       } 
  49.     } 
  50.   } 
  51. ‘@  
  52. $TAResults=$Supplier.CompileAssemblyFromSource($Params,$TASource) 
  53. $TAAssembly=$TAResults.CompiledAssembly 
  54.  
  55. ## We now create an occasion of the TrustAll and connect it to the ServicePointManager 
  56. $TrustAll=$TAAssembly.CreateInstance(“Native.ToolkitExtensions.Internet.CertificatePolicy.TrustAll“) 
  57. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll 
  58.  
  59. ## finish code from http://poshcode.org/624 
  60.    
  61. ## Set the URL of the CAS (Shopper Entry Server) to use two choices are availbe to use Autodiscover to discover the CAS URL or Hardcode the CAS to use   
  62.    
  63. #CAS URL Possibility 1 Autodiscover   
  64. $service.AutodiscoverUrl($MailboxName,{$true})   
  65. Utilizing CAS Server : ” + $Service.url    
  66.  
  67.  
  68.     
  69. #CAS URL Possibility 2 Hardcoded   
  70.    
  71. #$uri=[system.URI] “https://casservername/ews/alternate.asmx”   
  72. #$service.Url = $uri     
  73.    
  74. ## Non-obligatory part for Alternate Impersonation   
  75.    
  76. #$service.ImpersonatedUserId = new-object Microsoft.Alternate.WebServices.Knowledge.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)  
  77.  
  78. operate getPeopleRequest($offset){ 
  79.  
  80. $request = @”  
  81. <?xml model=“1.0” encoding=“utf-8”?>  
  82. <cleaning soap:Envelope xmlns:cleaning soap=“http://schemas.xmlsoap.org/cleaning soap/envelope/” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=“http://www.w3.org/2001/XMLSchema”>  
  83. <cleaning soap:Header>  
  84. <RequestServerVersion Model=“Alternate2013” xmlns=“http://schemas.microsoft.com/alternate/companies/2006/varieties” />  
  85. </cleaning soap:Header><cleaning soap:Physique>  
  86. <FindPeople xmlns=“http://schemas.microsoft.com/alternate/companies/2006/messages”><PersonaShape>  
  87. <BaseShape xmlns=“http://schemas.microsoft.com/alternate/companies/2006/varieties”>Default</BaseShape>  
  88. </PersonaShape><IndexedPageItemView MaxEntriesReturned=“100” Offset=“$offset” BasePoint=“Starting” />  
  89. <ParentFolderId>  
  90. <AddressListId Id=“$ABGUID” xmlns=“http://schemas.microsoft.com/alternate/companies/2006/varieties” />  
  91. </ParentFolderId></FindPeople></cleaning soap:Physique></cleaning soap:Envelope>  
  92. “@ 
  93. return $request 
  94. } 
  95.  
  96. operate getPersonaRequest($PersonalId){ 
  97. $request = @”  
  98. <?xml model=“1.0” encoding=“utf-8”?>  
  99. <cleaning soap:Envelope xmlns:cleaning soap=“http://schemas.xmlsoap.org/cleaning soap/envelope/”  
  100.                xmlns:t=“http://schemas.microsoft.com/alternate/companies/2006/varieties”>  
  101.   <cleaning soap:Header>  
  102.     <t:RequestServerVersion Model=“Alternate2013”/>  
  103.   </cleaning soap:Header>  
  104.   <cleaning soap:Physique xmlns=“http://schemas.microsoft.com/alternate/companies/2006/messages”>  
  105.     <GetPersona>  
  106.       <PersonaId Id=“$PersonalId”/>  
  107.     </GetPersona>  
  108.   </cleaning soap:Physique>  
  109. </cleaning soap:Envelope>  
  110. “@ 
  111. return $request 
  112. } 
  113.  
  114. operate AutoDiscoverPhotoURL{ 
  115.        param ( 
  116.               $EmailAddress=”$( throw ‘E-mail is a necessary Parameter’ )“, 
  117.               $Credentials=”$( throw ‘Credentials is a necessary Parameter’ ) 
  118.               ) 
  119.        course of{ 
  120.               $model= [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Alternate2013 
  121.               $adService= New-Object Microsoft.Alternate.WebServices.Autodiscover.AutodiscoverService($model); 
  122.               $adService.Credentials = $Credentials 
  123.               $adService.EnableScpLookup=$false; 
  124.               $adService.RedirectionUrlValidationCallback= {$true} 
  125.               $adService.PreAuthenticate=$true; 
  126.               $UserSettings= new-object Microsoft.Alternate.WebServices.Autodiscover.UserSettingName[] 1 
  127.               $UserSettings[0] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::ExternalPhotosUrl 
  128.               $adResponse=$adService.GetUserSettings($EmailAddress, $UserSettings) 
  129.               $PhotoURI= $adResponse.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::ExternalPhotosUrl] 
  130.               return $PhotoURI.ToString() 
  131.        } 
  132. } 
  133.  
  134. $Script:PhotoURL = AutoDiscoverPhotoURL -EmailAddress $MailboxName  -Credentials $creds 
  135. Write-host (“Photograph URL : ” + $Script:PhotoURL)  
  136.  
  137. operate ProcessPersona($PersonalId){ 
  138.  
  139.  
  140.     $personalRequest = getPersonaRequest ($PersonalId) 
  141.     $mbMailboxFolderURI = New-Object System.Uri($service.url)   
  142.     $wrWebRequest = [System.Net.WebRequest]::Create($mbMailboxFolderURI)   
  143.     $wrWebRequest.CookieContainer =  New-Object System.Internet.CookieContainer    
  144.     $wrWebRequest.KeepAlive = $false;   
  145.     $wrWebRequest.Headers.Set(“Pragma“, “no-cache“);   
  146.     $wrWebRequest.Headers.Set(“Translate“, “f“);   
  147.     $wrWebRequest.Headers.Set(“Depth“, “0“);   
  148.     $wrWebRequest.ContentType = “textual content/xml“;   
  149.     $wrWebRequest.ContentLength = $expRequest.Size;   
  150.     $wrWebRequest.Timeout = 90000;   
  151.     $wrWebRequest.Methodology = “POST“;   
  152.     $wrWebRequest.Credentials = $creds   
  153.     $wrWebRequest.UserAgent = “EWS Script 
  154.      
  155.     $bqByteQuery = [System.Text.Encoding]::ASCII.GetBytes($personalRequest);   
  156.     $wrWebRequest.ContentLength = $bqByteQuery.Size;   
  157.     $rsRequestStream = $wrWebRequest.GetRequestStream();   
  158.     $rsRequestStream.Write($bqByteQuery, 0, $bqByteQuery.Size);   
  159.     $rsRequestStream.Shut();   
  160.     $wrWebResponse = $wrWebRequest.GetResponse();   
  161.     $rsResponseStream = $wrWebResponse.GetResponseStream()   
  162.     $sr = new-object System.IO.StreamReader($rsResponseStream);   
  163.     $rdResponseDocument = New-Object System.Xml.XmlDocument   
  164.     $rdResponseDocument.LoadXml($sr.ReadToEnd());   
  165.     $Persona =@($rdResponseDocument.getElementsByTagName(“Persona“))  
  166.     $Persona 
  167.     $DisplayName = ““; 
  168.     if($Persona.DisplayName -ne $null){ 
  169.         $DisplayName = $Persona.DisplayName.”#textual content”  
  170.     }   
  171.     $fileName =  $exportFolder + $DisplayName + “-” + [Guid]::NewGuid().ToString() + “.vcf 
  172.     add-content -path $filename “BEGIN:VCARD 
  173.     add-content -path $filename “VERSION:2.1 
  174.     $givenName = “ 
  175.     if($Persona.GivenName -ne $null){ 
  176.         $givenName = $Persona.GivenName.”#textual content”  
  177.     }  
  178.     $surname = “ 
  179.     if($Persona.Surname -ne $null){ 
  180.         $surname = $Persona.Surname.”#textual content”  
  181.     }  
  182.     add-content -path $filename (“N:” + $surname + “;” + $givenName) 
  183.     add-content -path $filename (“FN:” + $Persona.DisplayName.”#textual content”)  
  184.     $Division = ““; 
  185.     if($Persona.Division -ne $null){ 
  186.         $Division = $Persona.Division.”#textual content”  
  187.     }  
  188.     if($Persona.EmailAddress -ne $null){  
  189.         add-content -path $filename (“EMAIL;PREF;INTERNET:” + $Persona.EmailAddress.EmailAddress) 
  190.     } 
  191.     $CompanyName = ““; 
  192.     if($Persona.CompanyName -ne $null){ 
  193.         $CompanyName = $Persona.CompanyName.”#textual content”  
  194.     }  
  195.     add-content -path $filename (“ORG:” + $CompanyName + “;” + $Division)  
  196.     if($Persona.Titles -ne $null){ 
  197.         add-content -path $filename (“TITLE:” + $Persona.Titles.StringAttributedValue.Worth) 
  198.     } 
  199.     if($Persona.MobilePhones -ne $null){ 
  200.         add-content -path $filename (“TEL;CELL;VOICE:” + $Persona.MobilePhones.PhoneNumberAttributedValue.Worth.Quantity)      
  201.     } 
  202.     if($Persona.HomePhones -ne $null){ 
  203.         add-content -path $filename (“TEL;HOME;VOICE:” + $Persona.HomePhones.PhoneNumberAttributedValue.Worth.Quantity)        
  204.     } 
  205.     if($Persona.BusinessPhoneNumbers -ne $null){ 
  206.         add-content -path $filename (“TEL;WORK;VOICE:” + $Persona.BusinessPhoneNumbers.PhoneNumberAttributedValue.Worth.Quantity)      
  207.     } 
  208.     if($Persona.WorkFaxes -ne $null){ 
  209.         add-content -path $filename (“TEL;WORK;FAX:” + $Persona.WorkFaxes.PhoneNumberAttributedValue.Worth.Quantity) 
  210.     } 
  211.     if($Persona.BusinessHomePages -ne $null){ 
  212.         add-content -path $filename (“URL;WORK:” + $Persona.BusinessHomePages.StringAttributedValue.Worth) 
  213.     } 
  214.     if($Persona.BusinessAddresses -ne $null){ 
  215.         $Nation = $Persona.BusinessAddresses.PostalAddressAttributedValue.Worth.Nation 
  216.         $Metropolis = $Persona.BusinessAddresses.PostalAddressAttributedValue.Worth.Metropolis 
  217.         $Road = $Persona.BusinessAddresses.PostalAddressAttributedValue.Worth.Road 
  218.         $State = $Persona.BusinessAddresses.PostalAddressAttributedValue.Worth.State 
  219.         $PCode = $Persona.BusinessAddresses.PostalAddressAttributedValue.Worth.PostalCode 
  220.         $addr =  “ADR;WORK;PREF:;” + $Nation + “;” + $Road + “;” +$Metropolis + “;” + $State + “;” + $PCode + “;” + $Nation 
  221.         add-content -path $filename $addr 
  222.     } 
  223.     strive{ 
  224.         $PhotoSize = “HR96x96”  
  225.         $PhotoURL= $Script:PhotoURL + “/GetUserPhoto?e-mail=”  + $Persona.EmailAddress.EmailAddress + “&measurement=” + $PhotoSize; 
  226.         $wbClient = new-object System.Internet.WebClient 
  227.         $wbClient.Credentials = $creds 
  228.         $photoBytes = $wbClient.DownloadData($PhotoURL); 
  229.         add-content -path $filename “PHOTO;ENCODING=BASE64;TYPE=JPEG: 
  230.         $ImageString = [System.Convert]::ToBase64String($photoBytes,[System.Base64FormattingOptions]::InsertLineBreaks) 
  231.         add-content -path $filename $ImageString 
  232.         add-content -path $filename “`r`n”   
  233.     } 
  234.     catch{ 
  235.  
  236.     } 
  237.     add-content -path $filename “END:VCARD 
  238.  
  239. } 
  240.  
  241. $peopleCollection = @() 
  242. $offset = 0; 
  243.  
  244. do{ 
  245.     $mbMailboxFolderURI = New-Object System.Uri($service.url)   
  246.     $wrWebRequest = [System.Net.WebRequest]::Create($mbMailboxFolderURI)   
  247.     $wrWebRequest.CookieContainer =  New-Object System.Internet.CookieContainer    
  248.     $wrWebRequest.KeepAlive = $false;   
  249.     $wrWebRequest.Useragent = “EWS Script 
  250.     $wrWebRequest.Headers.Set(“Pragma“, “no-cache“);   
  251.     $wrWebRequest.Headers.Set(“Translate“, “f“);   
  252.     $wrWebRequest.Headers.Set(“Depth“, “0“);   
  253.     $wrWebRequest.ContentType = “textual content/xml“;   
  254.     $wrWebRequest.ContentLength = $expRequest.Size;   
  255.     $wrWebRequest.Timeout = 60000;   
  256.     $wrWebRequest.Methodology = “POST“;   
  257.     $wrWebRequest.Credentials = $creds   
  258.  
  259.     $fpRequest = getPeopleRequest ($offset) 
  260.     $bqByteQuery = [System.Text.Encoding]::ASCII.GetBytes($fpRequest);   
  261.     $wrWebRequest.ContentLength = $bqByteQuery.Size;   
  262.     $rsRequestStream = $wrWebRequest.GetRequestStream();   
  263.     $rsRequestStream.Write($bqByteQuery, 0, $bqByteQuery.Size);   
  264.     $rsRequestStream.Shut();   
  265.     $wrWebResponse = $wrWebRequest.GetResponse();   
  266.     $rsResponseStream = $wrWebResponse.GetResponseStream()   
  267.     $sr = new-object System.IO.StreamReader($rsResponseStream);   
  268.     $rdResponseDocument = New-Object System.Xml.XmlDocument   
  269.     $rdResponseDocument.LoadXml($sr.ReadToEnd());   
  270.     $totalCount = @($rdResponseDocument.getElementsByTagName(“TotalNumberOfPeopleInView“))  
  271.     $Personas =@($rdResponseDocument.getElementsByTagName(“Persona“))   
  272.     Write-Host (“Individuals Rely : ” + $Personas.Rely) 
  273.     $offset += $Personas.Rely 
  274.     foreach($persona in $Personas){ 
  275.         if($persona.PersonaType -eq “Particular person“){ 
  276.             ProcessPersona($persona.PersonaId.Id.ToString())  
  277.         } 
  278.     } 
  279.     [Int32]$tc = $totalCount.”#textual content”  
  280.     Write-Host (“Offset: ” + $offset) 
  281.     Write-Host (“Whole depend: ” + $tc)  
  282.   
  283. }whereas($tc -gt $offset)