Monday, December 10, 2012

Multi Tabbed FreeBusy/OOF Board

In the past I've posted scripts for a Free-Busy Board and an OOF Board which uses the EWS Managed API and PowerShell. The following is a combination of the two that displays the OOFStatus of the user combined with their FreeBusy and Calendar Appointments in a Tabbed based output eg


To build the list of Mailboxes to create the Tabs the script uses a Distribution list and the ExpandDL operation which will retrieve a collection of SMTP address's for the members of the group. It then uses the GetUserAvailblity operation and MailTips operation to build the output.

To run the script you need to use the SMTPAddress of mailbox you want the script to run as and the SMTPAddress of the Distribution list to expand. eg

fbooftabs.ps1 user@domain.com dl@domain.com

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

  1. $tbRptSourceHeader=@' 
  2. <!DOCTYPE html> 
  3. <html lang="en"> 
  4. <head> 
  5. <style> 
  6. body 
  7. { 
  8.     font-family: "Segoe UI", arial, helvetica, freesans, sans-serif; 
  9.     font-size: 90%; 
  10.     color: #333; 
  11.     background-color: #e5eaff; 
  12.     margin: 10px; 
  13.     z-index: 0; 
  14. } 
  15.  
  16. h1 
  17. { 
  18.     font-size: 1.5em; 
  19.     font-weight: normal; 
  20.     margin: 0; 
  21. } 
  22.  
  23. h2 
  24. { 
  25.     font-size: 1.3em; 
  26.     font-weight: normal; 
  27.     margin: 2em 0 0 0; 
  28. } 
  29.  
  30. p 
  31. { 
  32.     margin: 0.6em 0; 
  33. } 
  34.  
  35. p.tabnav 
  36. { 
  37.     font-size: 1.1em; 
  38.     text-transform: uppercase; 
  39.     text-align: right; 
  40. } 
  41.  
  42. p.tabnav a 
  43. { 
  44.     text-decoration: none; 
  45.     color: #999; 
  46. } 
  47.  
  48. article.tabs 
  49. { 
  50.     position: relative; 
  51.     display: block; 
  52.     width: 80em; 
  53.     height: 30em; 
  54.     margin: 2em auto; 
  55. } 
  56.  
  57. article.tabs section 
  58. { 
  59.     position: absolute; 
  60.     display: block; 
  61.     top: 1.8em; 
  62.     left: 0; 
  63.     height: 42em; 
  64.     padding: 10px 20px; 
  65.     background-color: #ddd; 
  66.     border-radius: 5px; 
  67.     box-shadow: 0 3px 3px rgba(0,0,0,0.1); 
  68.     z-index: 0; 
  69. } 
  70.  
  71. article.tabs section:first-child 
  72. { 
  73.     z-index: 1; 
  74. } 
  75.  
  76. article.tabs section h2 
  77. { 
  78.     position: absolute; 
  79.     font-size: 1em; 
  80.     font-weight: normal; 
  81.     width: 120px; 
  82.     height: 1.8em; 
  83.     top: -1.8em; 
  84.     left: 10px; 
  85.     padding: 0; 
  86.     margin: 0; 
  87.     color: #999; 
  88.     background-color: #ddd; 
  89.     border-radius: 5px 5px 0 0; 
  90. } 
  91. '@   
  92.   
  93. $styleFooter=@' 
  94. article.tabs section h2 a 
  95. { 
  96.     display: block; 
  97.     width: 100%; 
  98.     line-height: 1.8em; 
  99.     text-align: center; 
  100.     text-decoration: none; 
  101.     color: inherit; 
  102.     outline: 0 none; 
  103. } 
  104.  
  105. article.tabs section, 
  106. article.tabs section h2 
  107. { 
  108.     -webkit-transition: all 500ms ease; 
  109.     -moz-transition: all 500ms ease; 
  110.     -ms-transition: all 500ms ease; 
  111.     -o-transition: all 500ms ease; 
  112.     transition: all 500ms ease; 
  113. } 
  114.  
  115. article.tabs section:target, 
  116. article.tabs section:target h2 
  117. { 
  118.     color: #333; 
  119.     background-color: #fff; 
  120.     z-index: 2; 
  121. } 
  122. </Style> 
  123. <meta charset="UTF-8" /> 
  124. <title>Tabbed FreeBusy-Out of Office Board</title> 
  125. <!--[if lt IE 9]> 
  126. <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
  127. <![endif]--> 
  128. </head> 
  129. <body> 
  130. <article class="tabs"> 
  131. '@  
  132. ## Get the Mailbox to Access from the 1st commandline argument  
  133.   
  134. $MailboxName = $args[0]  
  135.   
  136. ## Load Managed API dll    
  137. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  138.     
  139. ## Set Exchange Version    
  140. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  141.     
  142. ## Create Exchange Service Object    
  143. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  144.     
  145. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  146.     
  147. #Credentials Option 1 using UPN for the windows Account    
  148. $psCred = Get-Credential    
  149. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  150. $service.Credentials = $creds        
  151.     
  152. #Credentials Option 2    
  153. #service.UseDefaultCredentials = $true    
  154.     
  155. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  156.     
  157. ## Code From http://poshcode.org/624  
  158. ## Create a compilation environment  
  159. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  160. $Compiler=$Provider.CreateCompiler()  
  161. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  162. $Params.GenerateExecutable=$False  
  163. $Params.GenerateInMemory=$True  
  164. $Params.IncludeDebugInformation=$False  
  165. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  166.   
  167. $TASource=@' 
  168.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  169.     public class TrustAll : System.Net.ICertificatePolicy { 
  170.       public TrustAll() {  
  171.       } 
  172.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  173.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  174.         System.Net.WebRequest req, int problem) { 
  175.         return true; 
  176.       } 
  177.     } 
  178.   } 
  179. '@   
  180. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  181. $TAAssembly=$TAResults.CompiledAssembly  
  182.   
  183. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  184. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  185. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  186.   
  187. ## end code from http://poshcode.org/624  
  188.     
  189. ## 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    
  190.     
  191. #CAS URL Option 1 Autodiscover    
  192. $service.AutodiscoverUrl($MailboxName,{$true})    
  193. "Using CAS Server : " + $Service.url     
  194.      
  195. #CAS URL Option 2 Hardcoded    
  196.     
  197. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  198. #$service.Url = $uri      
  199.     
  200. ## Optional section for Exchange Impersonation    
  201.     
  202. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  203.   
  204.   
  205.   
  206. $fbGroup = $service.ExpandGroup($args[1]);  
  207. $StartTime = [DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 0:00"))  
  208. $EndTime = $StartTime.AddDays(1)  
  209.   
  210. $displayStartTime =  [DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 08:30"))  
  211. $tmValHash = @{ }  
  212. $tidx = 0  
  213.   
  214. for($vsStartTime=[DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 0:00"));$vsStartTime -lt [DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 0:00")).AddDays(1);$vsStartTime = $vsStartTime.AddMinutes(30)){  
  215.     $tmValHash.add($vsStartTime.ToString("HH:mm"),$tidx)      
  216.     $tidx++  
  217. }  
  218.     
  219. $drDuration = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($StartTime,$EndTime)    
  220. $AvailabilityOptions = new-object Microsoft.Exchange.WebServices.Data.AvailabilityOptions    
  221. $AvailabilityOptions.RequestedFreeBusyView = [Microsoft.Exchange.WebServices.Data.FreeBusyViewType]::DetailedMerged    
  222.    
  223. $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"  
  224. $type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.AttendeeInfo" -as "Type")  
  225. $Attendeesbatch = [Activator]::CreateInstance($type)   
  226. $mbrRequest = ""  
  227. foreach ($mbr in $fbGroup.Members){  
  228.     $Attendee = new-object Microsoft.Exchange.WebServices.Data.AttendeeInfo($mbr.Address)  
  229.     $mbrRequest = $mbrRequest + "<Mailbox xmlns=`"http://schemas.microsoft.com/exchange/services/2006/types`"><EmailAddress>" + $mbr.Address + "</EmailAddress></Mailbox>"   
  230.     $Attendeesbatch.add($Attendee)    
  231. }  
  232.   
  233. $attendeeOOFHash = @{}  
  234. ##Get OOF Status  
  235. $expHeader = @" 
  236. <?xml version="1.0" encoding="utf-8"?> 
  237. <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
  238. <soap:Header><RequestServerVersion Version="Exchange2010_SP1" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" /> 
  239. </soap:Header> 
  240. <soap:Body> 
  241. <GetMailTips xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"> 
  242. <SendingAs> 
  243. <EmailAddress xmlns="http://schemas.microsoft.com/exchange/services/2006/types">$MailboxName</EmailAddress> 
  244. </SendingAs> 
  245. <Recipients> 
  246. "@      
  247.       
  248.   
  249. $expRequest = $expHeader + $mbrRequest + "</Recipients><MailTipsRequested>OutOfOfficeMessage</MailTipsRequested></GetMailTips></soap:Body></soap:Envelope>"  
  250.   
  251. $mbMailboxFolderURI = New-Object System.Uri($service.url)  
  252. $wrWebRequest = [System.Net.WebRequest]::Create($mbMailboxFolderURI)  
  253. $wrWebRequest.CookieContainer =  New-Object System.Net.CookieContainer   
  254. $wrWebRequest.KeepAlive = $false;  
  255. $wrWebRequest.Headers.Set("Pragma""no-cache");  
  256. $wrWebRequest.Headers.Set("Translate""f");  
  257. $wrWebRequest.Headers.Set("Depth""0");  
  258. $wrWebRequest.ContentType = "text/xml";  
  259. $wrWebRequest.ContentLength = $expRequest.Length;  
  260. $wrWebRequest.Timeout = 60000;  
  261. $wrWebRequest.Method = "POST";  
  262. $wrWebRequest.Credentials = $creds  
  263. $bqByteQuery = [System.Text.Encoding]::ASCII.GetBytes($expRequest);  
  264. $wrWebRequest.ContentLength = $bqByteQuery.Length;  
  265. $rsRequestStream = $wrWebRequest.GetRequestStream();  
  266. $rsRequestStream.Write($bqByteQuery, 0, $bqByteQuery.Length);  
  267. $rsRequestStream.Close();  
  268. $wrWebResponse = $wrWebRequest.GetResponse();  
  269. $rsResponseStream = $wrWebResponse.GetResponseStream()  
  270. $sr = new-object System.IO.StreamReader($rsResponseStream);  
  271. $rdResponseDocument = New-Object System.Xml.XmlDocument  
  272. $rdResponseDocument.LoadXml($sr.ReadToEnd());  
  273. $RecipientNodes = @($rdResponseDocument.getElementsByTagName("t:RecipientAddress"))  
  274. $Datanodes = @($rdResponseDocument.getElementsByTagName("t:OutOfOffice"))  
  275. for($ic=0;$ic -lt $RecipientNodes.length;$ic++){  
  276.     if($Datanodes[$ic].ReplyBody.Message -eq ""){  
  277.         $attendeeOOFHash.add($Attendeesbatch[$ic].SmtpAddress,"In the Office")  
  278.     }  
  279.     else{  
  280.         $attendeeOOFHash.add($Attendeesbatch[$ic].SmtpAddress,"Out of the Office")  
  281.     }  
  282. }  
  283. ### End OOF  
  284.   
  285. $rptOutput = $tbRptSourceHeader  
  286.   
  287. $tabNumber = 1  
  288. $taboffset = 10  
  289. $SectionReport = ""  
  290.   
  291. $atndCnt = 0    
  292. $fbType = [Microsoft.Exchange.WebServices.Data.AvailabilityData]::FreeBusy  
  293. $availresponse = $service.GetUserAvailability($Attendeesbatch,$drDuration,$fbType,$AvailabilityOptions)    
  294. foreach($avail in $availresponse.AttendeesAvailability){    
  295.     if($tabNumber -eq 1){  
  296.           
  297.     }  
  298.     else{  
  299.         $taboffset+=122  
  300.         $rptOutput = $rptOutput + "article.tabs section:nth-child(" + $tabNumber +  ") h2 {     left: " + ($taboffset) + "px;}`r`n"   
  301.           
  302.     }  
  303.     $SectionReport = $SectionReport + "<section id=`"tab" + $tabNumber + "`">`r`n"  
  304.     $SectionReport = $SectionReport + "<h2><a href=`"#tab" + $tabNumber + "`">" + $Attendeesbatch[$atndCnt].SmtpAddress.SubString(0,10) + "</a></h2>`r`n"  
  305.     $SectionReport = $SectionReport + "<p>User : " + $Attendeesbatch[$atndCnt].SmtpAddress + "_________________________________________________________________________________________</p>`r`n"  
  306.     $SectionReport = $SectionReport + "<p>OOF Status : " + $attendeeOOFHash[$Attendeesbatch[$atndCnt].SmtpAddress] + "</p>`r`n"  
  307.     $SectionReport = $SectionReport + "<p>Number of Calendar Events : " + $avail.CalendarEvents.Count + "</p>`r`n"  
  308.     $SectionReport = $SectionReport + "<table><tr>" +"`r`n"  
  309.     $SectionReport = $SectionReport + "<td align=`"center`" style=`"width=200;`" ><b>Time</b></td>" +"`r`n"  
  310.     $SectionReport = $SectionReport + "<td align=`"center`" style=`"width=200;`" ><b>Status</b></td>" +"`r`n"  
  311.     $SectionReport = $SectionReport + "<td align=`"center`" style=`"width=200;`" ><b>Meetings</b></td>" +"`r`n"  
  312.     $SectionReport = $SectionReport + "</tr>"  
  313.   
  314.       
  315.     $tabNumber++  
  316.       
  317.     ""  
  318.     "User : " + $Attendeesbatch[$atndCnt].SmtpAddress  
  319.     "OOF Status : " + $attendeeOOFHash[$Attendeesbatch[$atndCnt].SmtpAddress]  
  320.     "Number of Calender Events : " + $avail.CalendarEvents.Count  
  321.   
  322.     $fbcnt = 0;  
  323.     for($stime = $displayStartTime;$stime -lt $displayStartTime.AddHours(10);$stime = $stime.AddMinutes(30)){  
  324.         $title = ""  
  325.         if ($avail.MergedFreeBusyStatus[$tmValHash[$stime.ToString("HH:mm")]] -eq "Busy" -bor $avail.MergedFreeBusyStatus[$tmValHash[$stime.ToString("HH:mm")]] -eq "OOF"){  
  326.             if ($avail.CalendarEvents.Count -ne 0){  
  327.                 for($ci=0;$ci -lt $avail.CalendarEvents.Count;$ci++){  
  328.                     if ($avail.CalendarEvents[$ci].StartTime -ge $stime -band $stime -le $avail.CalendarEvents[$ci].EndTime ){  
  329.                         if($avail.CalendarEvents[$ci].Details.IsPrivate -eq $False){  
  330.                             $subject = ""  
  331.                             $location = ""  
  332.                             if ($avail.CalendarEvents[$ci].Details.Subject -ne $null){  
  333.                                 $subject = $avail.CalendarEvents[$ci].Details.Subject.ToString()  
  334.                             }  
  335.                             if ($avail.CalendarEvents[$ci].Details.Location -ne $null){  
  336.                                 $location = $avail.CalendarEvents[$ci].Details.Location.ToString()  
  337.                             }  
  338.                             $title = $title + "`"" + $subject + " " + $location + "`" "  
  339.                         }  
  340.                     }  
  341.                 }  
  342.             }  
  343.         }  
  344.         $tbClr = "bgcolor=`"#41A317`""  
  345.         if($avail.MergedFreeBusyStatus[$tmValHash[$stime.ToString("HH:mm")]] -eq "Busy"){  
  346.             $tbClr = "bgcolor=`"#153E7E`""  
  347.         }  
  348.         $SectionReport = $SectionReport + "<tr>" +"`r`n"  
  349.         $SectionReport = $SectionReport + "<td align=`"center`" style=`"width=200;`" ><b>" + $stime.ToString("HH:mm") + " </b></td>" +"`r`n"  
  350.         $SectionReport = $SectionReport + "<td $tbClr align=`"center`" style=`"width=200;`" ><b>" + $avail.MergedFreeBusyStatus[$tmValHash[$stime.ToString("HH:mm")]] + "</b></td>" +"`r`n"  
  351.         $SectionReport = $SectionReport + "<td align=`"center`" style=`"width=200;`" ><b>" + $title + "</b></td>" +"`r`n"  
  352.         $SectionReport = $SectionReport + "</tr>"     
  353.         $stime.ToString("HH:mm") + " : " +  $avail.MergedFreeBusyStatus[$tmValHash[$stime.ToString("HH:mm")]] + " : " + $title  
  354.         $fbcnt++  
  355.     }  
  356.     $SectionReport = $SectionReport + "</table>"  
  357.     $SectionReport = $SectionReport + "</section>`r`n"  
  358.     $atndCnt++  
  359. }   
  360. $rptOutput = $rptOutput + $styleFooter + $SectionReport + "</article></body></html>"  
  361. $rptOutput | Out-File c:\temp\taboutput.htm  




Saturday, November 24, 2012

Create an RSS feed of Exchange Items using any of the How To Series scripts

If you've missed my HowTo Series this year I've been demonstrating many different way's of getting, filtering and searching for Exchange data using Powershell and the EWS Managed API see the full list here . One of the fun things to do with scripting is to link this together with the other plethora of script's out in the world to do different things. Here one example of linking the How-To series script with an RSS feed script from the PoshCode repository http://poshcode.org/?show=669

The following script grabs the last 50 Items in the Inbox and creates an RSS feed of theses Item including Links to OWA for the Item and the Item's Body as HTML in the Feed details.

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

  1. ###Code from http://poshcode.org/?show=669  
  2. # Creates an RSS feed  
  3. # Parameter input is for "site": Path, Title, Url, Description  
  4. # Pipeline input is for feed items: hashtable with Title, Link, Author, Description, and pubDate keys  
  5. Function New-RssFeed  
  6. {   
  7.     param (  
  8.             $Path = "$( throw 'Path is a mandatory parameter.' )",  
  9.             $Title = "Site Title",  
  10.             $Url = "http://$( $env:computername )",  
  11.             $Description = "Description of site"  
  12.     )  
  13.     Begin {  
  14.             # feed metadata  
  15.             $encoding = [System.Text.Encoding]::UTF8  
  16.             $writer = New-Object System.Xml.XmlTextWriter( $Path$encoding )  
  17.             $writer.WriteStartDocument()  
  18.             $writer.WriteStartElement( "rss" )  
  19.             $writer.WriteAttributeString( "version""2.0" )  
  20.             $writer.WriteStartElement( "channel" )  
  21.             $writer.WriteElementString( "title"$Title )  
  22.             $writer.WriteElementString( "link"$Url )  
  23.             $writer.WriteElementString( "description"$Description )  
  24.     }  
  25.     Process {  
  26.             # Construct feed items  
  27.             $writer.WriteStartElement( "item" )  
  28.             $writer.WriteElementString( "title",    $_.title )  
  29.             $writer.WriteElementString( "link",             $_.link )  
  30.             $writer.WriteElementString( "author",   $_.author )  
  31.             $writer.WriteStartElement( "description" )  
  32.             $writer.WriteRaw( "<![CDATA[" ) # desc can contain HTML, so its escaped using SGML escape code  
  33.             $writer.WriteRaw( $_.description )  
  34.             $writer.WriteRaw( "]]>" )  
  35.             $writer.WriteEndElement()  
  36.             $writer.WriteElementString( "pubDate"$_.pubDate.toString( 'r' ) )  
  37.             $writer.WriteElementString( "guid"$homePageUrl + "/" + [guid]::NewGuid() )  
  38.             $writer.WriteEndElement()  
  39.     }  
  40.     End {  
  41.             $writer.WriteEndElement()  
  42.             $writer.WriteEndElement()  
  43.             $writer.WriteEndDocument()  
  44.             $writer.Close()  
  45.     }  
  46. }  
  47. ### end code from http://poshcode.org/?show=669  
  48.   
  49. ## Get the Mailbox to Access from the 1st commandline argument  
  50.   
  51. $MailboxName = $args[0]  
  52.   
  53. ## Load Managed API dll    
  54. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"    
  55.     
  56. ## Set Exchange Version    
  57. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1    
  58.     
  59. ## Create Exchange Service Object    
  60. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  61.     
  62. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  63.     
  64. #Credentials Option 1 using UPN for the windows Account    
  65. $psCred = Get-Credential    
  66. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  67. $service.Credentials = $creds        
  68.     
  69. #Credentials Option 2    
  70. #service.UseDefaultCredentials = $true    
  71.     
  72. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  73.     
  74. ## Code From http://poshcode.org/624  
  75. ## Create a compilation environment  
  76. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  77. $Compiler=$Provider.CreateCompiler()  
  78. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  79. $Params.GenerateExecutable=$False  
  80. $Params.GenerateInMemory=$True  
  81. $Params.IncludeDebugInformation=$False  
  82. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  83.   
  84. $TASource=@' 
  85.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  86.     public class TrustAll : System.Net.ICertificatePolicy { 
  87.       public TrustAll() {  
  88.       } 
  89.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  90.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  91.         System.Net.WebRequest req, int problem) { 
  92.         return true; 
  93.       } 
  94.     } 
  95.   } 
  96. '@   
  97. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  98. $TAAssembly=$TAResults.CompiledAssembly  
  99.   
  100. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  101. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  102. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  103.   
  104. ## end code from http://poshcode.org/624  
  105.     
  106. ## 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    
  107.     
  108. #CAS URL Option 1 Autodiscover    
  109. $service.AutodiscoverUrl($MailboxName,{$true})    
  110. "Using CAS Server : " + $Service.url     
  111.      
  112. #CAS URL Option 2 Hardcoded    
  113.     
  114. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  115. #$service.Url = $uri      
  116.     
  117. ## Optional section for Exchange Impersonation    
  118.     
  119. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  120.   
  121. # Bind to the Contacts Folder  
  122.   
  123. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  124. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  125. $psPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  126. #Define ItemView to retrive just 50 Items      
  127. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(50)      
  128. $fiItems = $service.FindItems($Inbox.Id,$ivItemView)      
  129. [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  130. $feedItems = @()  
  131. foreach($Item in $fiItems.Items){      
  132.      "processing Item " + $Item.Subject  
  133.      $PostItem = @{}  
  134.      $PostItem.Add("Title",$Item.Subject)  
  135.      $PostItem.Add("Author",$Item.Sender.Address)  
  136.      $PostItem.Add("pubDate",$Item.DateTimeReceived)  
  137.      $PostItem.Add("link",("https://" + $service.Url.Host +  "/owa/" + $Item.WebClientReadFormQueryString))  
  138.      $PostItem.Add("description",$Item.Body.Text)  
  139.      $feedItems += $PostItem         
  140. }      
  141. $feedItems | New-RssFeed -path "c:\temp\Inboxfeed.xml" -title ($MailboxName + " Inbox")  


Thursday, November 15, 2012

Using eDiscovery to search mailboxes using EWS in Exchange 2013 (the new Exchange)

eDiscovery is one of the new features in Exchange 2013 that has been built on the top of new operations added in Exchange Web Services in 2013. While its very useful for ITPro's for handling legal discoveries and compliance issues, it opens up a whole new world for application developers building Apps that search Exchange Mailboxes. Like the AQS querystring that was introduced in Exchange 2010 the eDiscovery operations make use of the Exchange Search service's content indexes.

There isn't much documentation around at the moment about how to use eDiscovery in EWS so this is just a dump of what I've learned so far.

All up there are four new EWS operations for eDiscovery however the two that you will use most of the time would be.



GetSearchableMailboxes
Gets a list of mailboxes that the client has permission to search or perform eDiscovery on.
SearchMailboxes
Searches for items in specific mailboxes that match query keywords.

from http://msdn.microsoft.com/en-us/library/exchange/jj190897.aspx

Permissions wise you need to be a member of the Discovery Management RBAC role

The eDiscovery operations make use of the Keyword Query Language (KQL) which there is some decent documentation for in the Protocol documents for KQL http://msdn.microsoft.com/en-us/library/hh644280%28v=office.12%29.aspx although this isn't very Exchange specific. KQL is pretty cool and gives greater control and functionality over the queries you make when compared against AQS. The syntax does bare similarities to AQS and in some cases your AQS queries should just be transferable.

Some KQL samples would be

Subject:"New Time Proposed: test"  -  This would do an exact match on the Subject

Subject:Football    - This would do a SubString type query on the Subject

attachment:'.pdf'  - The would search for attachment with a pdf attachment

To use the new eDisocvery operations in the EWS Managed API you need to have v2.0 which was released recently http://www.microsoft.com/en-au/download/details.aspx?id=35371 .

So now it comes to using the SearchMaiboxes operation, to do this you need to have a properly formated KQL query and you need to know the Mailbox Identifier to use. The Mailbox identifier was a bit of tricky one where in most other things in EWS this would be the PrimarySMTPAddress, for this operation its the X500 (or legacyExchangedn) of the mailbox. There are a few ways you could get this the eaiest and most reliable would be to use the GetSearchableMailboxes operation to build the MailboxSearchScope array for the mailboxes you want to search . eg

  1. GetSearchableMailboxesResponse gsMBResponse = service.GetSearchableMailboxes("fsmith"false);  
  2. MailboxSearchScope[] msbScope = new MailboxSearchScope[gsMBResponse.SearchableMailboxes.Length];  
  3. Int32 mbCount = 0;  
  4. foreach (SearchableMailbox sbMailbox in gsMBResponse.SearchableMailboxes) {  
  5.     msbScope[mbCount] = new MailboxSearchScope(sbMailbox.ReferenceId, MailboxSearchLocation.All);  
  6.     mbCount++;  
  7. }  
The Important point is the ReferenceId (which is the X500 address) is the Id that SearchMailbox seems to want.
Next you build the actually request

  1. SearchMailboxesParameters smSearchMailbox = new SearchMailboxesParameters();  
  2. MailboxQuery mbq = new MailboxQuery("attachment:'.pdf'", msbScope);  
  3. MailboxQuery[] mbqa = new MailboxQuery[1] { mbq };  
  4. smSearchMailbox.SearchQueries = mbqa;  
  5. smSearchMailbox.PageSize = 1000;  
  6. smSearchMailbox.ResultType = Microsoft.Exchange.WebServices.Data.SearchResultType.PreviewOnly;  
  7. service.TraceEnabled = true;  
  8. ServiceResponseCollection<SearchMailboxesResponse> srCol =  service.SearchMailboxes(smSearchMailbox);  
There are a bunch of options for manipulating the results such as deduplication and the ability to page and sort the results in different ways and orders. You can also choose just to return the statistics of the query without the results, or return the resutls as PreviewItems where you can control what properties are returned in the PreviewItem.

So for me its a big thumbs up for eDiscovery, so far anyway I can see some frustrations in the way the PriviewItems are returned and there needs to be a lot better info for using KQL and the discovery options.