Monday, May 28, 2012

EWS Managed API and Powershell How-To Series Part 9 EWS Notifications

In this installment of the how-to series I'm going to cover EWS notifications which are a mechanism you can use to find out when changes occur in an Exchange Folder. One critical point when thinking about notifications is you need to think of them as notifications and not the programmatic equivalent of events which event sinks where (kind of). Exchange is a mail system that caters to many clients and applications and from a client sense (not a throttling sense) all of these clients are even. So when your building a notification application that is going to affect a message in some way(eg say your just moving it to another folder) you need to understand that by the time your application has received the notification another application may have taken an action on that message. The other issue you may have is because there can be so many clients involved and different synchronization methods in use is you may get multiple notifications for one item which is an issue you just need to make sure you cater for in your code. A good idea can be to look at combining notification operations with synchronization operations which I'll cover in a another post.

Event Notification Types

Before looking at the Types of notifications its a good idea to look at what type of events you can get notifications for.
  • NewMail - This notification fires when a new email is delivered to the Inbox
  • Modified - This notification fires when in Item is modified
  • Copy - This notification fires when an Item is copied
  • Created - This notification fires when a new Item is created in a folder (useful for monitoring the creation of Contacts,Task or Appointments)
  • Deleted - This notification fires when an Item is deleted (accessing the deleted Item is not trivial through)
  • Moved - This notification fires when an Item is moved.
  • FreeBusyChanged - This notification fires when FreeBusy status changes

Types of Notification's

Pull Notifications 

Pull notifications are client initiated notifications eg the way this would generally work is your client would first register for notifications at 10:00 AM on the Inbox, In the next hour 5 new emails arrive, your client then sends a request to the Exchange Server for new notifications on the Inbox at 11:00 AM and you receive back 5 notifications for the newly received messages. Pull notifications are good if your application isn't time critical and you just want to track changes at a regular interval. Here's an example of creating a pull notification on the Inbox folder for NewMail events and a simple update loop that will check for updates and bind to any updated items from the notification event when you press a key.

  1. $InboxId = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)  
  2. $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1  
  3. $fldArray[0] = $InboxId  
  4. $pullSubscription = $service.SubscribeToPullNotifications($fldArray,60,$null,[Microsoft.Exchange.WebServices.Data.EventType]::NewMail)  
  5. $events = $pullSubscription.GetEvents();  
  6. foreach ($notificationEvent in $events.AllEvents)  
  7. {    
  8.     switch ($notificationEvent.EventType)  
  9.       {  
  10.         "NewMail" {"New Mail"  
  11.                     $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  12.                     "Subject : " + $item.Subject  
  13.         }  
  14.       }  
  15. }  
  16. do{  
  17.     $response = read-host "Press key to check next events or Q to exits"  
  18.     $events = $pullSubscription.GetEvents();  
  19.     foreach ($notificationEvent in $events.AllEvents)  
  20.     {  
  21.         switch ($notificationEvent.EventType)  
  22.           {  
  23.             "NewMail" {"New Mail" 
  24.                     $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  25.                     "Subject : " + $item.Subject  
  26.                      }  
  27.                               
  28.           }  
  29.     }  
  30. }while($response -ne "Q")  
Subscribing to Notification events on all folders

In Exchange 2010 you can also subscribe to notifications on all folders in the EWS Managed API for pull notifications this is exposed as SubscribeToPullNotificationsOnAllFolders. The following is a sample of creating pull notifications on all folders in a mailbox this looks at the Modification events on Items.

  1. $pullSubscription = $service.SubscribeToPullNotificationsOnAllFolders(60,$null,[Microsoft.Exchange.WebServices.Data.EventType]::Modified)  
  2. $events = $pullSubscription.GetEvents();  
  3. foreach ($notificationEvent in $events.AllEvents)  
  4. {    
  5.     switch ($notificationEvent.EventType)  
  6.       {  
  7.             "Modified" {"Modified"  
  8.                     if($notificationEvent.ItemId -ne $null){  
  9.                         $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  10.                         "Subject : " + $item.Subject  
  11.                          }                     
  12.                         }  
  13.       }  
  14. }  
  15. do{  
  16.     $response = read-host "Press key to check next events or Q to exits"  
  17.     $events = $pullSubscription.GetEvents();  
  18.     foreach ($notificationEvent in $events.AllEvents)  
  19.     { 
  20.           {  
  21.             "Modified" {  
  22.                     if($notificationEvent.ItemId -ne $null){  
  23.                         $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  24.                         "Subject : " + $item.Subject  
  25.                          }  
  26.                      }  
  27.                               
  28.           }  
  29.     }  
  30. }while($response -ne "Q")  
Push Notifications

Push notifications are server initiated Notifications eg the way these work is at 10:00 AM you register for Push notifications on the Inbox for your client application with IP address 10.0.1.22. The next time an email arrives in the Inbox the Exchange server will then send a notification to your application. Push notifications are complex beasts in that you need to have a fairly complex application that listens for notifications and maintains the subscription. You also need to make sure you have a dedicated port and clear communication channels through firewalls etc. For this reason Push notifications aren't really practical to use with simple scripted type applications however the third type of notification Streaming Notification allow you to get all the benefits of Push notifications without the communication complexities.

Streaming Notifications

Streaming notifications work similar to push email in ActiveSync eg Your steaming notification application would register for streaming notifications at 10:00AM on the Inbox. The TCP connection used for the registration will then stay open and the Exchange Server will push notifications back to your application via this connection as new emails arrive in the Inbox. Which means you get push notifications without needing a dedicated listener application or the need to worry about firewalls etc. The only catch with streaming notification is that they have a maximum duration of 30 minutes so in the example I've been talking about at 10:30AM you would need to recreate the streaming notification subscription. The good thing is that there are events that are triggered by the Managed API's StreamingSubscriptionConnection class they we can hook in Powershell so we can have a self renewing subscription process. In Powershell the Register-ObjectEvent cmdlet allows you to subscribe to the events that are generated by the Microsoft .NET Framework. To use Streaming notifications in Powershell you need to register for events that are generated by the StreamingSubscriptionConnection class. An example of a Streaming Notification script that will listen for the NewMail Event on the Inbox looks like

  1. $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1  
  2. $Inboxid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)  
  3. $fldArray[0] = $Inboxid  
  4. $stmsubscription = $service.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)  
  5. $stmConnection = new-object Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection($service, 30);  
  6. $stmConnection.AddSubscription($stmsubscription)  
  7. Register-ObjectEvent -inputObject $stmConnection -eventName "OnNotificationEvent" -Action {  
  8.     foreach($notEvent in $event.SourceEventArgs.Events){      
  9.         [String]$itmId = $notEvent.ItemId.UniqueId.ToString()  
  10.         $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($event.MessageData,$itmId)  
  11.         "Subject : " + $message.Subject + " " + (Get-Date) | Out-File c:\temp\log2.txt -Append   
  12.     }   
  13. } -MessageData $service  
  14. Register-ObjectEvent -inputObject $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()} -MessageData $stmConnection  
  15. $stmConnection.Open()  
To register for Streaming notifications on all folders you can use SubscribeToStreamingNotificationsOnAllFolders

Tuesday, May 08, 2012

How To Series Sample 6 : Show a sorted list of Subject's and number of messages within a mailbox

The following script shows how you can create a summary report of the Subjects of all Messages within a Mailbox. It makes use of the PR_NORMALIZED_SUBJECT http://msdn.microsoft.com/en-us/library/cc815282.aspx. property which contains the subject of a message minus the prefixes such as RE, FW etc. The end result is it will pump out a sorted list of the Number of messages per subject and also create a CSV report. The script is designed to work on Exchange 2010 but you could make it work on 2007 as well by converting the AQS QueryString (which limits the finditems call to just Email) to a search filter. I've put a download of this script here the script looks like
  1. $RptObjColl = @()  
  2. $MailboxName = "user@domain.com"  
  3.   
  4. ## Load Managed API dll    
  5. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll"    
  6.     
  7. ## Set Exchange Version    
  8. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1    
  9.     
  10. ## Create Exchange Service Object    
  11. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  12.     
  13. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  14.     
  15. #Credentials Option 1 using UPN for the windows Account    
  16. $creds = New-Object System.Net.NetworkCredential("user@domain.com","password")     
  17. $service.Credentials = $creds        
  18.     
  19. #Credentials Option 2    
  20. #service.UseDefaultCredentials = $true    
  21.     
  22. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  23.     
  24. [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}    
  25.     
  26. ## 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    
  27.     
  28. #CAS URL Option 1 Autodiscover    
  29. $service.AutodiscoverUrl($MailboxName,{$true})    
  30. "Using CAS Server : " + $Service.url     
  31.      
  32. #CAS URL Option 2 Hardcoded    
  33.     
  34. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  35. #$service.Url = $uri      
  36.     
  37. ## Optional section for Exchange Impersonation    
  38.     
  39. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  40.   
  41. # Bind to the Archive Root folder    
  42. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)     
  43. $MsgRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  44.   
  45. $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  46. #Deep Transval will ensure all folders in the search path are returned   
  47.    
  48. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  49. $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  50. #The Search filter will exclude any Search Folders   
  51. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  52. $PR_NORMALIZED_SUBJECT = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E1D,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);     
  53. $psPropertySet.add($PR_NORMALIZED_SUBJECT)  
  54. $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);    
  55. $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")    
  56. $fiResult = $null    
  57. #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox   
  58. $rptHash = @{}  
  59. $AQSString = "kind:email"   
  60. do {   
  61.     $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  62.     $ivItemView.PropertySet = $psPropertySet  
  63.     $fiResult = $Service.FindFolders($folderid,$sfSearchFilter,$fvFolderView)    
  64.     foreach($ffFolder in $fiResult.Folders){    
  65.     "Processing Folder : " + $ffFolder.displayName   
  66.     if($ffFolder.UnreadCount -gt 0){  
  67.         $fiResults = $null  
  68.         $updateColl = @()  
  69.         do{    
  70.             $fiResults = $ffFolder.findItems($AQSString,$ivItemView)  
  71.             foreach($Item in $fiResults.Items){    
  72.                 $subject = $null  
  73.                 if($Item.TryGetProperty($PR_NORMALIZED_SUBJECT,[ref]$subject)){  
  74.                     if($subject -ne $null){  
  75.                         "Processing Messsage : " + $subject  
  76.                         if($rptHash.Contains($subject) -eq $false){  
  77.                             $rptHash.add($subject,1);  
  78.                         }  
  79.                         else{  
  80.                             $rptHash[$subject] +=1  
  81.                         }  
  82.                     }  
  83.                 }  
  84.             }    
  85.             $ivItemView.Offset += $fiResults.Items.Count    
  86.         }while($fiResults.MoreAvailable -eq $true)  
  87.     }           
  88.     }   
  89.     $fvFolderView.Offset += $fiResult.Folders.Count  
  90. }while($fiResult.MoreAvailable -eq $true)   
  91.   
  92. $rptHash.GetEnumerator() | Sort-Object value -Descending | ForEach-Object{  
  93.     $rptobj = "" | select Subject, NumberofMessages  
  94.     $rptobj.Subject = $_.Key  
  95.     $rptobj.NumberofMessages = $_.Value  
  96.     $RptObjColl += $rptobj  
  97. }  
  98. $RptObjColl | Export-Csv -NoTypeInformation -path c:\temp\subjectReport.csv  
  99. $RptObjColl  

Monday, May 07, 2012

EWS Managed API and Powershell How-To Series Part 8 Folder Permissions

In this series so far I've covered a lot of ground in EWS covering all the everyday operations so its time now to look at some of the more interesting and useful things you can do. Folder permissions are one thing that can both affect the code you run if you don't have the correct or enough rights in a folder your accessing and are also something you may want to manage using EWS. As before in this series I should point out that folder permission can be managed within the Exchange Management Shell using the Get and Set-MailboxFolderPermissions cmdlets and this can be a better solution for managing permissions.

Exchange Folder permission in a netshell

Exchange uses the normal discretionary access control list (DACL) with Access Control Entries (ACE's) to control access to its resources but there are a few special things to keep in mind. (There are also SACL's on public folders which you can't set from EWS).

Special ACE's in the Folder DACL : There are two special Group ACE's in a Exchange DACL there is the Default ACE (basically every authenticated mailbox user) and the Anoymous ACE (more for public folders which im not really going to dicuss).

FreeBusy Permissions : In Exchange 2007 freebusy rights where introduced see http://blogs.msdn.com/b/stephen_griffin/archive/2007/05/25/new-freebusy-rights-in-exchange-outlook-2007.aspx . So if your accessing the calendar folder in a users mailbox in EWS you will use a different class to accommodate these extra free-busy permissions.

Let's start by looking at some samples, to access the permission on a users Inbox you can use the following

  1. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  2. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  3. foreach($Permission in $Inbox.Permissions){  
  4.     if($Permission.UserId.StandardUser -eq $null){  
  5.         "User : " + $Permission.UserId.PrimarySmtpAddress  
  6.     }  
  7.     else{  
  8.         "User : " + $Permission.UserId.StandardUser.ToString()  
  9.     }  
  10.     $Permission  
  11. }  
To show the FreeBusy Permissions on the Calendar Folder

  1. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)     
  2. $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  3. foreach($Permission in $Calendar.Permissions){  
  4.     $rptObj = "" | Select User,FreeBusyRights  
  5.     if($Permission.UserId.StandardUser -eq $null){  
  6.         $rptObj.User = $Permission.UserId.PrimarySmtpAddress  
  7.         $rptObj.FreeBusyRights = $Permission.ReadItems  
  8.     }  
  9.     else{  
  10.         $rptObj.User = $Permission.UserId.StandardUser.ToString()  
  11.         $rptObj.FreeBusyRights = $Permission.ReadItems  
  12.     }  
  13.     $rptObj  
  14. }  
Modifying Folder Permissions

When you want to modify folder permission using EWS you first need to get the existing ACL from the folder check to see if there is an existing ACE for the user you want to add/modify and either change the existing ACE's permission or delete it and  add a new ACE (what you are trying to avoid is duplicating the ACE which will cause an error). Here is an example of adding reviewer rights for a specific user to the Inbox in this code if it detects an existing ACE it just removes that ACE and adds a new one with reviewer rights.

  1. $UsertoAdd = "user@domain.comm"  
  2. $PermissiontoAdd = [Microsoft.Exchange.WebServices.Data.FolderPermissionLevel]::Reviewer  
  3. $existingperm = $null  
  4. foreach($fperm in $Inbox.Permissions){  
  5.     if($fperm.UserId.PrimarySmtpAddress -ne $null){  
  6.         if($fperm.UserId.PrimarySmtpAddress.ToLower() -eq $UsertoAdd.ToLower()){  
  7.                 $existingperm = $fperm  
  8.         }  
  9.     }  
  10. }  
  11. if($existingperm -ne $null){  
  12.     $Inbox.Permissions.Remove($existingperm)  
  13. }   
  14. $newfp = new-object Microsoft.Exchange.WebServices.Data.FolderPermission($UsertoAdd,$PermissiontoAdd)  
  15. $Inbox.Permissions.Add($newfp)  
  16. $Inbox.Update()  
Special considerations for the Calendar Folder

When working with calendar folder permissions you should also make sure you mirror any changes that you make to the Freebusy folder in the Non_IPM_Subtree if you don't do this you may find that you cant modify appointments even though you have rights in the folder. Eg the following is an example of giving the Default ACE (which essentially means everybody) editor access to a calendar.

  1. function addFolderPerm($folder){    
  2.     $existingperm = $null    
  3.     foreach($fperm in $folder.Permissions){    
  4.         if($fperm.UserId.StandardUser -eq $null){    
  5.             if ($fperm.UserId.PrimarySmtpAddress.ToLower() -eq $NewACLUser.ToLower()){    
  6.                 $existingperm = $fperm    
  7.             }    
  8.         }    
  9.     }    
  10.     if($existingperm -ne $null){    
  11.         $folder.Permissions.Remove($existingperm)    
  12.     }     
  13.     $newfp = new-object Microsoft.Exchange.WebServices.Data.FolderPermission($NewACLUser,$Permission)    
  14.     $folder.Permissions.Add($newfp)    
  15.     $folder.Update()    
  16. }    
  17.     
  18. "Checking : " + $MailboxName     
  19. $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)    
  20. $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderidcnt)    
  21. "Set Calendar Rights"    
  22. addFolderPerm($Calendar)    
  23. $sf1 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"Freebusy Data")    
  24.     
  25. $fvFolderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  26. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Shallow;    
  27.     
  28. $folderidRoot = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)    
  29. $fiResult = $Service.FindFolders($folderidRoot,$sf1,$fvFolderView)    
  30. if($fiResult.Folders.Count -eq 1){    
  31.     "Set FreeBusy Rights"    
  32.     $Freebusyfld = $fiResult.Folders[0]    
  33.     $Freebusyfld.Load()    
  34.     addFolderPerm($Freebusyfld)    
  35. }    

Reporting on all Shared folders in a Mailbox

Here's a full script that will enumerate every folder in a mailbox and check all the ACE's and report on any folders that are shared.

  1. $ReportingCollection = @()  
  2. $MailboxName = "user@domain.com"  
  3.   
  4. ## Load Managed API dll    
  5. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll"    
  6.     
  7. ## Set Exchange Version    
  8. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1    
  9.     
  10. ## Create Exchange Service Object    
  11. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  12.     
  13. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  14.     
  15. #Credentials Option 1 using UPN for the windows Account    
  16. $creds = New-Object System.Net.NetworkCredential("user@domain.com","password")     
  17. $service.Credentials = $creds        
  18.     
  19. #Credentials Option 2    
  20. #service.UseDefaultCredentials = $true    
  21.     
  22. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  23.     
  24. [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}    
  25.     
  26. ## 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    
  27.     
  28. #CAS URL Option 1 Autodiscover    
  29. $service.AutodiscoverUrl($MailboxName,{$true})    
  30. "Using CAS Server : " + $Service.url     
  31.      
  32. #CAS URL Option 2 Hardcoded    
  33.     
  34. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  35. #$service.Url = $uri      
  36.     
  37. ## Optional section for Exchange Impersonation   
  38.   
  39. function ConvertToString($ipInputString){    
  40.     $Val1Text = ""    
  41.     for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){    
  42.             $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))    
  43.             $clInt++    
  44.     }    
  45.     return $Val1Text    
  46. }    
  47.     
  48. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  49.   
  50. # Bind to the Archive Root folder    
  51. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)     
  52. $fldRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  53.   
  54. $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  55. #Deep Transval will ensure all folders in the search path are returned   
  56.    
  57. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  58. $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  59. #The Search filter will exclude any Search Folders   
  60. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  61. $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);     
  62. $psPropertySet.Add($PR_Folder_Path);    
  63. $fvFolderView.PropertySet = $psPropertySet;   
  64. $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);    
  65. $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")    
  66. $fiResult = $null    
  67. do {    
  68.     $fiResult = $Service.FindFolders($folderid,$sfSearchFilter,$fvFolderView)    
  69.     foreach($ffFolder in $fiResult.Folders){    
  70.         $foldpathval = $null  
  71.         if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))    
  72.         {    
  73.             $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)    
  74.             $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }    
  75.             $hexString = $hexArr -join ''    
  76.             $hexString = $hexString.Replace("FEFF""5C00")    
  77.             $fpath = ConvertToString($hexString)    
  78.         }    
  79.         "Processing : "  + $fpath  
  80.         $ffFolder.Load()  
  81.         foreach($Permission in $ffFolder.Permissions){    
  82.             if($Permission.PermissionLevel -ne [Microsoft.Exchange.WebServices.Data.FolderPermissionLevel]::None){  
  83.                 $rptobj = "" | Select FolderPath, User, Permission  
  84.                 if($Permission.UserId.StandardUser -eq $null){   
  85.                     $rptobj.FolderPath = $fpath  
  86.                     $rptobj.User = $Permission.UserId.PrimarySmtpAddress   
  87.                     $rptobj.Permission = $Permission.PermissionLevel  
  88.                     $ReportingCollection += $rptobj  
  89.                 }    
  90.                 else{    
  91.                     $rptobj.FolderPath = $fpath  
  92.                     $rptobj.User = $Permission.UserId.StandardUser.ToString()   
  93.                     $rptobj.Permission = $Permission.PermissionLevel  
  94.                     $ReportingCollection += $rptobj     
  95.                 }    
  96.             }  
  97.         }           
  98.     }   
  99.     $fvFolderView.Offset += $fiResult.Folders.Count  
  100. }while($fiResult.MoreAvailable -eq $true)   
  101.   
  102. $ReportingCollection  
  103. $ReportingCollection | Export-Csv -NoTypeInformation -Path c:\temp\sharedfolders.csv