Thursday, October 31, 2013

Creating a Shared Calendar Shortcut (WunderBar Link) with EWS and Powershell

Shared Calendar Shortcuts eg



are an Outlook and OWA  feature that can be handy to automate if you need to deploy a number of these to new (or existing) mailboxes and you don't want to go through the invitation/accept procedure or manually adding each shortcut.

While there are no supported operations in EWS for creating these type of objects, it can be achieved by setting the Extended MAPI properties that constitute the shortcut. The downside of this is that it wouldn't ever be considered supported if it all goes horribly wrong. The properties involved in the shortcut are documented in the following protocol document http://msdn.microsoft.com/en-us/library/ee157359(v=exchg.80).aspx.

For a couple of these properties the values you need to get can't be obtained directly in EWS so some others tricks are needed.

The PidTagWlinkAddressBookEID property contains the MAPI address Book EntryId for the shared Calendar your connecting to. The Address Book EntryID format is documented here http://msdn.microsoft.com/en-us/library/ee160588%28v=exchg.80%29.aspx so to construct this in EWS you need to get the LegacyExchangeDN from AutoDiscover and then appended the ProviderUID,Flag and Type information which for a normal user will be the same. (Note if you are trying to connect to an object other then a user mailbox.

The PidTagWlinkAddressBookStoreEID proeprty contains the MAPI StoreEntryID of the users where your creating the ShortCut. While you can get this property in EWS the value you get isn't correct because EWS uses different wrapper and providerID values. So instead using the format documented in http://msdn.microsoft.com/en-us/library/ee203516%28v=exchg.80%29.aspx you can construct this which involves getting the LegacyExchangeDN and the ServerName for Autodiscover and then building the identifier.

The other properties are pretty static for shared calendars.

The ShortCuts them selves are saved in a Non_IPM_Subtree folder called common views

(Special thanks also to Neil Doody for helping with property definitions in this post and script)

So the following script takes two commandline parameter the first is the Mailbox where you want the shortcut to be created and the second is the Mailbox which has the Calendar you want the shortcut to point to so you would run it like

./createWBarCal.ps1 user@domain.com target@domain.com

 The script will check the CommonViews folder to see if a SharedFolder shortcut already exists for the target Mailbox AddressId and FolderType and if no ShortCut exists and it will attempt to create one.

As i mentioned before as this script is completely unsupported and for the most part untested and should only be considered safe for testing in a development\test environment. It also assume you have Autodiscover working if not your this isn't going to work well.

 I've put a download of the script here the code itself looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2. $TargetCalendarMailbox = $args[1]  
  3. $MailboxName = $args[0]  
  4.   
  5. ## Load Managed API dll    
  6. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  7.     
  8. ## Set Exchange Version    
  9. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  10.     
  11. ## Create Exchange Service Object    
  12. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  13.     
  14. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  15.     
  16. #Credentials Option 1 using UPN for the windows Account    
  17. $psCred = Get-Credential    
  18. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  19. $service.Credentials = $creds        
  20.     
  21. #Credentials Option 2    
  22. #service.UseDefaultCredentials = $true    
  23.     
  24. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  25.     
  26. ## Code From http://poshcode.org/624  
  27. ## Create a compilation environment  
  28. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  29. $Compiler=$Provider.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 Local.ToolkitExtensions.Net.CertificatePolicy{ 
  38.     public class TrustAll : System.Net.ICertificatePolicy { 
  39.       public TrustAll() {  
  40.       } 
  41.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  42.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  43.         System.Net.WebRequest req, int problem) { 
  44.         return true; 
  45.       } 
  46.     } 
  47.   } 
  48. '@   
  49. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  50. $TAAssembly=$TAResults.CompiledAssembly  
  51.   
  52. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  53. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  54. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  55.   
  56. ## end code from http://poshcode.org/624  
  57.     
  58. ## 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    
  59.     
  60. #CAS URL Option 1 Autodiscover    
  61. $service.AutodiscoverUrl($MailboxName,{$true})    
  62. "Using CAS Server : " + $Service.url     
  63.      
  64. #CAS URL Option 2 Hardcoded    
  65.     
  66. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  67. #$service.Url = $uri      
  68.     
  69. ## Optional section for Exchange Impersonation    
  70.     
  71. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  72.   
  73. function GetAutoDiscoverSettings{  
  74.     param (  
  75.             $adEmailAddress = "$( throw 'emailaddress is a mandatory Parameter' )",  
  76.             $Credentials = "$( throw 'Credentials is a mandatory Parameter' )"  
  77.           )  
  78.     process{  
  79.         $adService = New-Object Microsoft.Exchange.WebServices.AutoDiscover.AutodiscoverService($ExchangeVersion);  
  80.         $adService.Credentials = $Credentials  
  81.         $adService.EnableScpLookup = $false;  
  82.         $adService.RedirectionUrlValidationCallback = {$true}  
  83.         $UserSettings = new-object Microsoft.Exchange.WebServices.Autodiscover.UserSettingName[] 3  
  84.         $UserSettings[0] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN  
  85.         $UserSettings[1] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::InternalRpcClientServer  
  86.         $UserSettings[2] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDisplayName  
  87.         $adResponse = $adService.GetUserSettings($adEmailAddress , $UserSettings);  
  88.         return $adResponse  
  89.     }  
  90. }  
  91. function GetAddressBookId{  
  92.     param (  
  93.             $AutoDiscoverSettings = "$( throw 'AutoDiscoverSettings is a mandatory Parameter' )"  
  94.           )  
  95.     process{  
  96.         $userdnString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN]  
  97.         $userdnHexChar = $userdnString.ToCharArray();  
  98.         foreach ($element in $userdnHexChar) {$userdnStringHex = $userdnStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}  
  99.         $Provider = "00000000DCA740C8C042101AB4B908002B2FE1820100000000000000"  
  100.         $userdnStringHex = $Provider + $userdnStringHex + "00"  
  101.         return $userdnStringHex  
  102.     }  
  103. }  
  104. function GetStoreId{  
  105.     param (  
  106.             $AutoDiscoverSettings = "$( throw 'AutoDiscoverSettings is a mandatory Parameter' )"  
  107.           )  
  108.     process{  
  109.         $userdnString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN]  
  110.         $userdnHexChar = $userdnString.ToCharArray();  
  111.         foreach ($element in $userdnHexChar) {$userdnStringHex = $userdnStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}   
  112.         $serverNameString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::InternalRpcClientServer]  
  113.         $serverNameHexChar = $serverNameString.ToCharArray();  
  114.         foreach ($element in $serverNameHexChar) {$serverNameStringHex = $serverNameStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}  
  115.         $flags = "00000000"  
  116.         $ProviderUID = "38A1BB1005E5101AA1BB08002B2A56C2"  
  117.         $versionFlag = "0000"  
  118.         $DLLFileName = "454D534D44422E444C4C00000000"  
  119.         $WrappedFlags = "00000000"  
  120.         $WrappedProviderUID = "1B55FA20AA6611CD9BC800AA002FC45A"  
  121.         $WrappedType = "0C000000"  
  122.         $StoredIdStringHex = $flags + $ProviderUID + $versionFlag + $DLLFileName + $WrappedFlags + $WrappedProviderUID + $WrappedType + $serverNameStringHex + "00" + $userdnStringHex + "00"  
  123.         return $StoredIdStringHex  
  124.     }  
  125. }  
  126.   
  127.   
  128. function hex2binarray($hexString){  
  129.     $i = 0  
  130.     [byte[]]$binarray = @()  
  131.     while($i -le $hexString.length - 2){  
  132.         $strHexBit = ($hexString.substring($i,2))  
  133.         $binarray += [byte]([Convert]::ToInt32($strHexBit,16))  
  134.         $i = $i + 2  
  135.     }  
  136.     return ,$binarray  
  137. }  
  138. function ConvertId($EWSid){      
  139.     $aiItem = New-Object Microsoft.Exchange.WebServices.Data.AlternateId        
  140.     $aiItem.Mailbox = $MailboxName        
  141.     $aiItem.UniqueId = $EWSid     
  142.     $aiItem.Format = [Microsoft.Exchange.WebServices.Data.IdFormat]::EWSId;        
  143.     return $service.ConvertId($aiItem, [Microsoft.Exchange.WebServices.Data.IdFormat]::StoreId)       
  144. }   
  145.   
  146. #PropDefs   
  147. $pidTagStoreEntryId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(4091, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  148. $PidTagNormalizedSubject = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E1D,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);   
  149. $PidTagWlinkType = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6849, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  150. $PidTagWlinkFlags = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684A, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  151. $PidTagWlinkOrdinal = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684B, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  152. $PidTagWlinkFolderType = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684F, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  153. $PidTagWlinkSection = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6852, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  154. $PidTagWlinkGroupHeaderID = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6842, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  155. $PidTagWlinkSaveStamp = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6847, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  156. $PidTagWlinkGroupName = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6851, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)  
  157. $PidTagWlinkStoreEntryId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684E, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  158. $PidTagWlinkGroupClsid = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6850, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  159. $PidTagWlinkEntryId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684C, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  160. $PidTagWlinkRecordKey = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684D, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  161. $PidTagWlinkCalendarColor = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6853, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  162. $PidTagWlinkAddressBookEID = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6854,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  163. $PidTagWlinkROGroupType = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6892,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  164. $PidTagWlinkAddressBookStoreEID = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6891,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  165.   
  166.   
  167. #Get the TargetUsers Calendar  
  168. # Bind to the Calendar Folder  
  169. $fldPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  170. $fldPropset.Add($pidTagStoreEntryId);  
  171. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$TargetCalendarMailbox)     
  172. $TargetCalendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid,$fldPropset)  
  173. #Check for existing ShortCut for TargetMailbox  
  174. #Get AddressBook Id for TargetUser  
  175. Write-Host ("Getting Autodiscover Settings Target")  
  176. Write-Host ("Getting Autodiscover Settings Mailbox")  
  177. $adset = GetAutoDiscoverSettings -adEmailAddress $MailboxName -Credentials $creds  
  178. $storeID = ""  
  179. if($adset -is [Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverResponse]){  
  180.     Write-Host ("Get StoreId")  
  181.     $storeID = GetStoreId -AutoDiscoverSettings $adset  
  182. }  
  183. $adset = $null  
  184. $abTargetABEntryId = ""  
  185. $adset = GetAutoDiscoverSettings -adEmailAddress $TargetCalendarMailbox -Credentials $creds  
  186. if($adset -is [Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverResponse]){  
  187.     Write-Host ("Get AB Id")  
  188.     $abTargetABEntryId = GetAddressBookId -AutoDiscoverSettings $adset  
  189.     $SharedUserDisplayName =  $adset.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDisplayName]  
  190. }  
  191. Write-Host ("Getting CommonVeiwFolder")  
  192. #Get CommonViewFolder  
  193. $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)     
  194. $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)    
  195. $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)   
  196. $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"Common Views")   
  197. $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)   
  198. if ($findFolderResults.TotalCount -gt 0){   
  199.     $ExistingShortCut = $false  
  200.     $cvCommonViewsFolder = $findFolderResults.Folders[0]  
  201.     #Define ItemView to retrive just 1000 Items      
  202.     #Find Items that are unread  
  203.     $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  204.     $psPropset.add($PidTagWlinkAddressBookEID)  
  205.     $psPropset.add($PidTagWlinkFolderType)  
  206.     $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)     
  207.     $ivItemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated  
  208.     $ivItemView.PropertySet = $psPropset  
  209.     $fiItems = $service.FindItems($cvCommonViewsFolder.Id,$ivItemView)      
  210.     foreach($Item in $fiItems.Items){  
  211.         $aeidVal = $null  
  212.         if($Item.TryGetProperty($PidTagWlinkAddressBookEID,[ref]$aeidVal)){  
  213.                 $fldType = $null  
  214.                 if($Item.TryGetProperty($PidTagWlinkFolderType,[ref]$fldType)){  
  215.                     if([System.BitConverter]::ToString($fldType).Replace("-","") -eq "0278060000000000C000000000000046"){  
  216.                         if([System.BitConverter]::ToString($aeidVal).Replace("-","") -eq $abTargetABEntryId){  
  217.                             $ExistingShortCut = $true  
  218.                             Write-Host "Found existing Shortcut"  
  219.                             ###$Item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete)  
  220.                         }  
  221.                     }  
  222.                 }  
  223.             }                               
  224.     }  
  225.     if($ExistingShortCut -eq $false){  
  226.         If($storeID.length -gt 5 -band $abTargetABEntryId.length -gt 5){  
  227.             $objWunderBarLink = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service    
  228.             $objWunderBarLink.Subject = $SharedUserDisplayName    
  229.             $objWunderBarLink.ItemClass = "IPM.Microsoft.WunderBar.Link"    
  230.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkAddressBookEID,(hex2binarray $abTargetABEntryId))    
  231.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkAddressBookStoreEID,(hex2binarray $storeID))    
  232.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkCalendarColor,-1)  
  233.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkFlags,0)  
  234.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkGroupName,"Shared Calendars")  
  235.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkFolderType,(hex2binarray "0278060000000000C000000000000046"))    
  236.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkGroupClsid,(hex2binarray "B9F0060000000000C000000000000046"))    
  237.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkROGroupType,-1)  
  238.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkSection,3)    
  239.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkType,2)    
  240.             $objWunderBarLink.IsAssociated = $true  
  241.             $objWunderBarLink.Save($findFolderResults.Folders[0].Id)  
  242.             Write-Host ("ShortCut Created for - " + $SharedUserDisplayName)  
  243.         }  
  244.         else{  
  245.             Write-Host ("Error with Id's")  
  246.         }  
  247.     }  
  248. }  






Monday, October 21, 2013

Exporting the Suggested Contacts, OWA Auto-complete Cache and Recipient Cache in Exchange 2013 with EWS and PowerShell

The following script creates a CSV export of Automatically generated contacts that have been saved in any of the 3 following auto contact locations

Suggested Contacts Folder which is Outlook feature that automatically creates a Contact for each address you send an email to - http://office.microsoft.com/en-au/outlook-help/automatically-add-contacts-for-everyone-that-you-send-an-email-message-HA101874367.aspx

OWA Autocomplete Cache - This is OWA version of the NickName cache, its stored in a UserConfiguration object in the Root of the Mailbox. The Addresses are stored inside an XML Streaming Property.

Recipeints Cache Folder - This is a new Exchange 2013 folder which is a hidden sub folder of the Contacts folder with a mailbox and it's purpose isn't really documented at the moment, but contains like the AutoComplete cache,  Addresses for Sent Emails.

So this script just create a CSV file with the Source, DisplayName and Email-address of any entries from these 3 locations.

I've put a download of this script here

The code looks like


  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2.   
  3. $MailboxName = $args[0]  
  4.   
  5. ## Load Managed API dll    
  6. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  7.     
  8. ## Set Exchange Version    
  9. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013  
  10.     
  11. ## Create Exchange Service Object    
  12. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  13.     
  14. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  15.     
  16. #Credentials Option 1 using UPN for the windows Account    
  17. $psCred = Get-Credential    
  18. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  19. $service.Credentials = $creds        
  20.     
  21. #Credentials Option 2    
  22. #service.UseDefaultCredentials = $true    
  23.     
  24. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  25.     
  26. ## Code From http://poshcode.org/624  
  27. ## Create a compilation environment  
  28. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  29. $Compiler=$Provider.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 Local.ToolkitExtensions.Net.CertificatePolicy{ 
  38.     public class TrustAll : System.Net.ICertificatePolicy { 
  39.       public TrustAll() {  
  40.       } 
  41.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  42.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  43.         System.Net.WebRequest req, int problem) { 
  44.         return true; 
  45.       } 
  46.     } 
  47.   } 
  48. '@   
  49. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  50. $TAAssembly=$TAResults.CompiledAssembly  
  51.   
  52. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  53. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  54. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  55.   
  56. ## end code from http://poshcode.org/624  
  57.     
  58. ## 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    
  59.     
  60. #CAS URL Option 1 Autodiscover    
  61. $service.AutodiscoverUrl($MailboxName,{$true})    
  62. "Using CAS Server : " + $Service.url     
  63.      
  64. #CAS URL Option 2 Hardcoded    
  65.     
  66. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  67. #$service.Url = $uri      
  68.     
  69. ## Optional section for Exchange Impersonation    
  70.     
  71. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  72. $ExportCollection = @()  
  73. Write-Host "Process Recipient Cache"  
  74. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::RecipientCache,$MailboxName)     
  75. $RecipientCache = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  76.   
  77. $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  78. #Define ItemView to retrive just 1000 Items      
  79. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)      
  80. $fiItems = $null      
  81. do{      
  82.     $fiItems = $service.FindItems($RecipientCache.Id,$ivItemView)      
  83.     [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  84.     foreach($Item in $fiItems.Items){       
  85.         if($Item -is [Microsoft.Exchange.WebServices.Data.Contact]){  
  86.             $expObj = "" | select Source,DisplayName,Email1DisplayName,Email1Type,Email1EmailAddress  
  87.             $expObj.Source = "RecipientCache"  
  88.             $expObj.DisplayName = $Item.DisplayName  
  89.             if($Item.EmailAddresses.Contains([Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1)){                  
  90.                 $expObj.Email1DisplayName = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Name  
  91.                 $expObj.Email1Type = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].RoutingType  
  92.                 $expObj.Email1EmailAddress = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Address  
  93.             }  
  94.             $ExportCollection += $expObj  
  95.         }  
  96.     }      
  97.     $ivItemView.Offset += $fiItems.Items.Count      
  98. }while($fiItems.MoreAvailable -eq $true)   
  99.   
  100. Write-Host "Process Suggested Contacts"  
  101. $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)   
  102. $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)  
  103. $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"Suggested Contacts")  
  104. $findFolderResults = $service.FindFolders($folderid,$SfSearchFilter,$fvFolderView)  
  105.   
  106. if($findFolderResults.Folders.Count -gt 0){  
  107.     $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  108.     #Define ItemView to retrive just 1000 Items      
  109.     $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)      
  110.     $fiItems = $null      
  111.     do{      
  112.         $fiItems = $service.FindItems($findFolderResults.Folders[0].Id,$ivItemView)      
  113.         [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  114.         foreach($Item in $fiItems.Items){       
  115.             if($Item -is [Microsoft.Exchange.WebServices.Data.Contact]){  
  116.                 $expObj = "" | select Source,DisplayName,Email1DisplayName,Email1Type,Email1EmailAddress  
  117.                 $expObj.Source = "Suggested Contacts"  
  118.                 $expObj.DisplayName = $Item.DisplayName  
  119.                 if($Item.EmailAddresses.Contains([Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1)){                  
  120.                     $expObj.Email1DisplayName = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Name  
  121.                     $expObj.Email1Type = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].RoutingType  
  122.                     $expObj.Email1EmailAddress = $Item.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1].Address  
  123.                 }  
  124.                 $ExportCollection += $expObj  
  125.             }  
  126.         }      
  127.         $ivItemView.Offset += $fiItems.Items.Count      
  128.     }while($fiItems.MoreAvailable -eq $true)   
  129. }  
  130. Write-Host "Process OWA AutocompleteCache"  
  131. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)   
  132. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)       
  133. #Specify the Calendar folder where the FAI Item is    
  134. $UsrConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service"OWA.AutocompleteCache"$folderid, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)    
  135. #Get the XML in String Format    
  136. $acXML = [System.Text.Encoding]::UTF8.GetString($UsrConfig.XmlData)    
  137. #Deal with the first character being a Byte Order Mark    
  138. $boMark = $acXML.SubString(0,1)    
  139. #Parse the XML    
  140. [XML]$acXML = $acXML.SubString(1)    
  141. foreach($AcEnt in $acXML.AutoCompleteCache.Entry){  
  142.     $expObj = "" | select Source,DisplayName,Email1DisplayName,Email1Type,Email1EmailAddress  
  143.     $expObj.Source = "OWA AutocompleteCache"  
  144.     $expObj.DisplayName = $AcEnt.displayName  
  145.     $expObj.Email1DisplayName= $AcEnt.displayName  
  146.     $expObj.Email1Type= "SMTP"  
  147.     $expObj.Email1EmailAddress= $AcEnt.smtpAddr  
  148.     $ExportCollection +=$expObj   
  149. }  
  150. $fnFileName = "c:\temp\" + $MailboxName + "AC-CacheExport.csv" 
  151. $ExportCollection | Export-Csv -NoTypeInformation -Path $fnFileName 
  152. "Exported to " + $fnFileName  

Thursday, October 10, 2013

Parsing out URL's in the body of a Message with EWS and Powershell

Sometimes when your writing an Automation script you might want to parse a certain URL from the Body of a Message. One example would be the Lync Meeting URL from an Online Meeting invitation or another might but a DropBox URL for a shared file.

To grab the Body of a Message in the EWS Managed API you need to use either Load() or LoadPropertiesForItems() if you have a number of messages your processing. Using these methods will do a GetItem (or batch GetItem) in EWS.

To parse the URL's from the HTML body markup that EWS returns you can use some RegEx to separate out all the links. Then you can use the URI class from .net to parse the matches further and identify the hosts in the URL to see if its the URL your looking for. The following sample will loop through the last 100 emails in a mailbox's and parse any Lync Meeting URL's (for Office365) or Dropbox URL's.

I've put a download of this script here

The code looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2.   
  3. $MailboxName = $args[0]  
  4.   
  5. ## Load Managed API dll    
  6. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  7.     
  8. ## Set Exchange Version    
  9. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  10.     
  11. ## Create Exchange Service Object    
  12. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  13.     
  14. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  15.     
  16. #Credentials Option 1 using UPN for the windows Account    
  17. $psCred = Get-Credential    
  18. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  19. $service.Credentials = $creds        
  20.     
  21. #Credentials Option 2    
  22. #service.UseDefaultCredentials = $true    
  23.     
  24. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  25.     
  26. ## Code From http://poshcode.org/624  
  27. ## Create a compilation environment  
  28. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  29. $Compiler=$Provider.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 Local.ToolkitExtensions.Net.CertificatePolicy{ 
  38.     public class TrustAll : System.Net.ICertificatePolicy { 
  39.       public TrustAll() {  
  40.       } 
  41.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  42.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  43.         System.Net.WebRequest req, int problem) { 
  44.         return true; 
  45.       } 
  46.     } 
  47.   } 
  48. '@   
  49. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  50. $TAAssembly=$TAResults.CompiledAssembly  
  51.   
  52. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  53. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  54. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  55.   
  56. ## end code from http://poshcode.org/624  
  57.     
  58. ## 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    
  59.     
  60. #CAS URL Option 1 Autodiscover    
  61. $service.AutodiscoverUrl($MailboxName,{$true})    
  62. "Using CAS Server : " + $Service.url     
  63.      
  64. #CAS URL Option 2 Hardcoded    
  65.     
  66. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  67. #$service.Url = $uri      
  68.     
  69. ## Optional section for Exchange Impersonation    
  70. $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  71. # Bind to the Inbox Folder  
  72. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  73. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  74.   
  75. #Define ItemView to retrive just 1000 Items      
  76. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(100)      
  77. $fiItems = $service.FindItems($Inbox.Id,$ivItemView)      
  78. [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  79. foreach($Item in $fiItems.Items){        
  80.     #Process Item    
  81.     "Processing : " + $Item.Subject  
  82.     $dupChk = @{}  
  83.     $RegExHtmlLinks = "<a href=\`"(.*?)\`">"  
  84.     $matchedItems = [regex]::matches($Item.Body, $RegExHtmlLinks,[system.Text.RegularExpressions.RegexOptions]::Singleline)  
  85.     foreach($Match in $matchedItems){  
  86.         $SplitVal = $Match.Value.Split('"')  
  87.         if($SplitVal.Count -gt 0){  
  88.             $ParsedURI=[system.URI]$SplitVal[1]  
  89.             if($ParsedURI.Host -eq "meet.lync.com"){ 
  90.                 if(!$dupChk.Contains($ParsedURI.AbsoluteUri)){ 
  91.                     Write-Host -ForegroundColor Green   "LyncURL     : " + $ParsedURI.AbsoluteUri 
  92.                     $dupChk.add($ParsedURI.AbsoluteUri,0) 
  93.                 } 
  94.             }  
  95.             if($ParsedURI.Host -eq "www.dropbox.com"){ 
  96.                 if(!$dupChk.Contains($ParsedURI.AbsoluteUri)){ 
  97.                     Write-Host -ForegroundColor Blue "DropBox    : " + $ParsedURI.AbsoluteUri  
  98.                     $dupChk.add($ParsedURI.AbsoluteUri,0)  
  99.                 }  
  100.             }    
  101.         }  
  102.     }  
  103. }