Friday, September 28, 2012

Finding and removing Duplicate Items with EWS and Powershell (MEC Sample)

This is the first of a number of samples I'll be posting (in no specific order) from the talk I gave at MEC thanks to all those that did brave my talk and all the other people I got to talk with about EWS over the conference. For me MEC the missing conference was really unmissable and would recommend if you didn't catch it this time look out for it in the future also check out the new community site iammec.

So let's look at the method this script uses to detect duplicates, firstly there are a number of way that dups can be created and the method this script uses won't work in every situation so it's important to understand how it works. The primary Extended Property this script uses to detect duplicate Items is the pidTagSearchKey (or PR_Search_Key) http://msdn.microsoft.com/en-us/library/office/cc815908.aspx . If you read this link or your a fan of using a MAPI editor like me you would know that this property is used on both the Item and on the recipients in the recipients collection. The reason this property is useful for finding duplicates is that its "Unique in the Entire World" and doesn't change during a copy operation. So for cases where users have incorrectly copied Items (folder to folder, pst to mailbox, mailbox to archive) or they have been copied/Imported by some other method (and there are many) this should work. Where it won't work is when you just have a rouge app or piece of code that creates Items because each newly created Item in this case would have a unique SearchKey in that case you'll need to pick another property you want to use. As a secondary property this script uses the ReceivedTime which also shouldn't change when you copy an Item. The other thing to be careful of with this method is if the duplicates have been around for a while and you have changes being made to one of the duplicates and not the other. This script won't delete any duplicates it finds within a folder instead it will create a folder in the DeletedItems folder called detected duplicates with the datetime the script ran and it will then copy those detected duplicates to this folder. So if all goes wrong you have the ability to copy the items back otherwise they will get deleted when the user empties their deletedItems folder (which maybe never).

This script has one other new piece of code that I came up with for MEC which is the folder selector code snipit so unlike a lot of the scripts I've shown before where you need to set the Mailbox folder you want to work with or use some code to find that folder if its not a well-known folder when you run this script it will first do a findfolder operation to grab all the folders in a mailbox. It will then build a TreeView of all the Mailbox Folders and then present a GUI that will allow you to select what mailbox folder you want to work with.eg

 

 Then the rest of the code will run based on the doubleclick event on the particular leaf you select and doubleclick. The EWS FolderId is stored and retrieved from the tag property of each leaf of the treeview. I've latched this script meaning you need to confirm every duplicate it finds but I've also now added an all option which means if you don't want to have to confirm every Item you can just say yes once.

To run this script just pass in the primary SMTPAddress of the mailbox you want to run it against and it will prompt for the credentials. eg  .\finddups.ps1 mec@msgdevelop.onmicrosoft.com

I've put a download copy of the script here the code itself look 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\1.2\Microsoft.Exchange.WebServices.dll"    
  7. [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")   
  8. [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")   
  9.     
  10. ## Set Exchange Version    
  11. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  12.     
  13. ## Create Exchange Service Object    
  14. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  15.     
  16. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  17.     
  18. #Credentials Option 1 using UPN for the windows Account    
  19. $psCred = Get-Credential    
  20. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  21. $service.Credentials = $creds        
  22. $service.EnableScpLookup = $false  
  23.     
  24. #Credentials Option 2    
  25. #service.UseDefaultCredentials = $true    
  26.     
  27. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  28.     
  29. ## Code From http://poshcode.org/624  
  30. ## Create a compilation environment  
  31. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  32. $Compiler=$Provider.CreateCompiler()  
  33. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  34. $Params.GenerateExecutable=$False  
  35. $Params.GenerateInMemory=$True  
  36. $Params.IncludeDebugInformation=$False  
  37. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  38.   
  39. $TASource=@' 
  40.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  41.     public class TrustAll : System.Net.ICertificatePolicy { 
  42.       public TrustAll() {  
  43.       } 
  44.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  45.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  46.         System.Net.WebRequest req, int problem) { 
  47.         return true; 
  48.       } 
  49.     } 
  50.   } 
  51. '@   
  52. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  53. $TAAssembly=$TAResults.CompiledAssembly  
  54.   
  55. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  56. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  57. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  58.   
  59. ## end code from http://poshcode.org/624  
  60.     
  61. ## 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    
  62.     
  63. #CAS URL Option 1 Autodiscover    
  64. $service.AutodiscoverUrl($MailboxName,{$true})    
  65. "Using CAS Server : " + $Service.url     
  66.      
  67. #CAS URL Option 2 Hardcoded    
  68.     
  69. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  70. #$service.Url = $uri      
  71.     
  72. ## Optional section for Exchange Impersonation    
  73.     
  74. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  75. #Define Extended properties    
  76. $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);    
  77. $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)    
  78. # Bind to the Contacts Folder  
  79.   
  80. $rfRootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderidcnt)  
  81.   
  82. #Define the FolderView used for Export should not be any larger then 1000 folders due to throttling    
  83. $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  84. #Deep Transval will ensure all folders in the search path are returned    
  85. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  86. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  87. $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);    
  88. #Add Properties to the  Property Set    
  89. $psPropertySet.Add($PR_Folder_Path);    
  90. $fvFolderView.PropertySet = $psPropertySet;    
  91. #The Search filter will exclude any Search Folders    
  92. $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")    
  93. $fiResult = $null    
  94. #  
  95.   
  96. $Treeinfo = @{}  
  97. $TNRoot = new-object System.Windows.Forms.TreeNode("Root")  
  98. $TNRoot.Name = "Mailbox"  
  99. $TNRoot.Text = "Mailbox - " + $MailboxName  
  100. #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox    
  101. do {    
  102.     $fiResult = $Service.FindFolders($folderidcnt,$sfSearchFilter,$fvFolderView)    
  103.     foreach($ffFolder in $fiResult.Folders){     
  104.         #Process folder here  
  105.         $TNChild = new-object System.Windows.Forms.TreeNode($ffFolder.DisplayName.ToString())  
  106.         $TNChild.Name = $ffFolder.DisplayName.ToString()  
  107.         $TNChild.Text = $ffFolder.DisplayName.ToString()  
  108.         $TNChild.tag = $ffFolder.Id.UniqueId.ToString()  
  109.         if ($ffFolder.ParentFolderId.UniqueId -eq $rfRootFolder.Id.UniqueId ){  
  110.             $ffFolder.DisplayName  
  111.             [void]$TNRoot.Nodes.Add($TNChild)   
  112.             $Treeinfo.Add($ffFolder.Id.UniqueId.ToString(),$TNChild)  
  113.         }  
  114.         else{  
  115.             $pfFolder = $Treeinfo[$ffFolder.ParentFolderId.UniqueId.ToString()]  
  116.             [void]$pfFolder.Nodes.Add($TNChild)  
  117.             if ($Treeinfo.ContainsKey($ffFolder.Id.UniqueId.ToString()) -eq $false){  
  118.                 $Treeinfo.Add($ffFolder.Id.UniqueId.ToString(),$TNChild)  
  119.             }  
  120.         }  
  121.     }   
  122.     $fvFolderView.Offset += $fiResult.Folders.Count  
  123. }while($fiResult.MoreAvailable -eq $true)    
  124. $Script:clickedFolder = $null  
  125. $objForm = New-Object System.Windows.Forms.Form   
  126. $objForm.Text = "Folder Select Form"  
  127. $objForm.Size = New-Object System.Drawing.Size(600,600)   
  128. $objForm.StartPosition = "CenterScreen"  
  129. $tvTreView1 = new-object System.Windows.Forms.TreeView  
  130. $tvTreView1.Location = new-object System.Drawing.Size(1,1)   
  131. $tvTreView1.add_DoubleClick({  
  132.     $Script:clickedFolder = $this.SelectedNode.tag  
  133.     $objForm.Close()  
  134. })  
  135. $tvTreView1.size = new-object System.Drawing.Size(580,580)   
  136. $tvTreView1.Anchor = "Top,left,Bottom"  
  137. [void]$tvTreView1.Nodes.Add($TNRoot)   
  138. $objForm.controls.add($tvTreView1)  
  139. $objForm.ShowDialog()  
  140.   
  141. $clickedfolderid = new-object Microsoft.Exchange.WebServices.Data.FolderId($Script:clickedFolder)     
  142.   
  143. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::DeletedItems,$MailboxName)     
  144. $DuplicatesFolder = New-Object Microsoft.Exchange.WebServices.Data.Folder -ArgumentList $service  
  145. $DuplicatesFolder.DisplayName = "DuplicateItems-Deduped-" + (Get-Date).ToString("yyyy-MM-dd-hh-mm-ss")  
  146. $DuplicatesFolder.Save($folderid)  
  147.   
  148. #Define ItemView to retrive just 1000 Items  
  149. $PidTagSearchKey = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x300B, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  150. $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  151. $psPropset.add($PidTagSearchKey)  
  152.   
  153. $dupHash = @{}  
  154.   
  155. #Create Collection for Move Batch  
  156. $Itemids = @()  
  157. $script:allChoice = $false  
  158.   
  159. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)      
  160. $ivItemView.PropertySet = $psPropset  
  161. $fiItems = $null      
  162. do{      
  163.     $fiItems = $service.FindItems($clickedfolderid,$ivItemView)      
  164.     #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  165.     foreach($Item in $fiItems.Items){  
  166.         $PropVal =  $null  
  167.         if($Item.TryGetProperty($PidTagSearchKey,[ref]$PropVal)){  
  168.             $SearchString = [System.BitConverter]::ToString($PropVal).Replace("-","")  
  169.             if($dupHash.ContainsKey($SearchString)){  
  170.                 #Check the recivedDate if availible  
  171.                 if($Item.DateTimeReceived -ne $null){  
  172.                     if($Item.DateTimeReceived -eq $dupHash[$SearchString]){  
  173.                         if($script:allChoice -eq $false){  
  174.                             $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",""  
  175.                             $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No",""  
  176.                             $all = new-Object System.Management.Automation.Host.ChoiceDescription "&All","";  
  177.                             $choices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no,$all)  
  178.                             $message = "Duplicated Detected : Subject " + $Item.Subject + " : Received-" + $dupHash[$SearchString] + " : Created-" + $Item.DateTimeCreated  
  179.                             $result = $Host.UI.PromptForChoice($caption,$message,$choices,0)  
  180.                             if($result -eq 0) {                       
  181.                                 $Itemids += $Item                         
  182.                             }  
  183.                             else{  
  184.                                 if($result -eq 2){  
  185.                                     $script:allChoice = $true  
  186.                                     $Itemids += $Item  
  187.                                 }  
  188.                             }  
  189.                         }  
  190.                         else{  
  191.                             $Itemids += $Item  
  192.                         }  
  193.                     }                     
  194.                 }else{  
  195.                     "Duplicate Found : " + $Item.Subject  
  196.                     $Itemids += $Item  
  197.                 }  
  198.             }  
  199.             else{  
  200.                 "Procesing Item " + $Item.Subject  
  201.                 if($Item.DateTimeReceived -ne $null){  
  202.                     $dupHash.add($SearchString,$Item.DateTimeReceived)  
  203.                 }  
  204.                 else{  
  205.                     $dupHash.add($SearchString,"")  
  206.                 }  
  207.             }  
  208.         }          
  209.     }      
  210.     $ivItemView.Offset += $fiItems.Items.Count      
  211. }while($fiItems.MoreAvailable -eq $true)   
  212.   
  213. #Total Items Processed Varible  
  214. $nmbProcessed = 0  
  215. if($Itemids.Count -gt 0){  
  216.     write-host ("Move " + $Itemids.Count + " Items")  
  217.     #Create Collection for Move Batch  
  218.     $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"  
  219.     $type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.ItemId" -as "Type")  
  220.     $BatchItemids = [Activator]::CreateInstance($type)  
  221.     #Varible to Track BatchSize  
  222.     $batchSize = 0  
  223.     foreach($iiID in $Itemids){  
  224.         $nmbProcessed++  
  225.         $BatchItemids.Add($iiID.Id)  
  226.         if($iiID.Size -ne $null){  
  227.             $batchSize += $iiID.Size  
  228.         }  
  229.         #if BatchCount greator then 50 or larger the 10 MB Move Batch  
  230.         if($BatchItemids.Count -eq 50 -bor $batchSize -gt (10*1MB)){  
  231.             $Result = $null  
  232.             $Result = $service.MoveItems($BatchItemids,$DuplicatesFolder.Id)  
  233.             [INT]$collectionCount = 0  
  234.             [INT]$Rcount = 0    
  235.             [INT]$Errcount = 0  
  236.             $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"  
  237.             $type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.ItemId" -as "Type")  
  238.             #Define Collection to Retry Move For faild Items  
  239.             if($Result -ne $null){  
  240.                 foreach ($res in $Result){   
  241.                     if ($res.Result -eq [Microsoft.Exchange.WebServices.Data.ServiceResult]::Success){    
  242.                         $Rcount++    
  243.                     }   
  244.                     else{  
  245.                         $Errcount++  
  246.                     }  
  247.                     $collectionCount++  
  248.                 }    
  249.             }  
  250.             else{  
  251.                 Write-Host -foregroundcolor red ("Move Result Null Exception")  
  252.             }  
  253.             Write-host ($Rcount.ToString() + " Items Moved Successfully " + "Total Processed " + $nmbProcessed + " Total Folder Items " + $Itemids.Count)   
  254.             if($Errcount -gt 0){  
  255.                 Write-Host -foregroundcolor red ($Errcount.ToString() + " Error failed Moved")  
  256.             }  
  257.             $BatchItemids.Clear()  
  258.             $batchSize = 0  
  259.         }  
  260.     }  
  261.     if($BatchItemids.Count -gt 0){  
  262.         $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"  
  263.         $type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.ItemId" -as "Type")  
  264.         $RetryBatchItemids = [Activator]::CreateInstance($type)  
  265.         $Result = $service.MoveItems($BatchItemids,$DuplicatesFolder.Id)   
  266.         [INT]$Rcount = 0    
  267.         [INT]$Errcount = 0   
  268.         foreach ($res in $Result){    
  269.             if ($res.Result -eq [Microsoft.Exchange.WebServices.Data.ServiceResult]::Success){    
  270.                 $Rcount++    
  271.             }    
  272.             else{  
  273.                 $Errcount++  
  274.             }  
  275.         }    
  276.         Write-host ($Rcount.ToString() + " Items Moved Successfully")  
  277.   
  278.         if($Errcount -gt 0){  
  279.             Write-Host -foregroundcolor red ($Errcount.ToString() + " Error failed Moved")  
  280.         }  
  281.     }  
  282. }  
  283. $DuplicatesFolder.Load()  
  284. if($DuplicatesFolder.TotalCount -eq 0){  
  285.     $DuplicatesFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)  
  286. }  





Monday, September 10, 2012

Reporting on the Outlook Client Junk Email filter with EWS and Powershell

Within most Exchange Orgs there are multiple levels of SPAM and junk email filtering that may include Cloud based first level filtering like Postini and Forefront and then other server based filters like those standard AS features that come with the Transport Server role with Exchange 2010. At the client level if you have the Outlook 200x junk email filter enabled it will also be providing another level of Junk Email filtering.  The one difference being that while the cloud and server based solutions filter email while it is in the Transport Pipeline the client based filter will only filter it once it has arrived in a Mailbox folder and it can also filter content such as RSS feeds that don't come via the transport mechanism.

Although inevitably the Junk Email ends up in the Junk Email folder when the client  side filter takes action on an Item it adds some extra Extended properties that can be used from a reporting perspective. The most interesting is

PidLidSpamOriginalFolder http://msdn.microsoft.com/en-us/library/office/cc765862.aspx

This reflects the original Mailbox Folder where the Email was filtered from. When using this property in a EWS script you will get the HexEntryID of the original folder which you then need to convert to an EWSID using the convert-ID operation to make use of in EWS.

So I've put together the followng script that will report on a Mailbox's JunkEmail folder and tell if any of the Items have been filtered by the Server or Client and if they where filtered by the Client what the original folder was that the email came from . To Run the script you need to supply it with the PrimarySMTPAddress of the account you want to run it against (eg ./jmreport.ps1 mailbox@domain.com)  and it will then output the result to c:\temp.

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

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2. $rptCollection = @()  
  3. $MailboxName = $args[0]  
  4.   
  5. ## Load Managed API dll    
  6. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\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. # Bind to the Inbox Folder  
  74. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$MailboxName)     
  75. $JunkEmail = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  76.   
  77. $PidLidSpamOriginalFolder = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,0x859C, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  78. $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  79. $psPropset.Add($PidLidSpamOriginalFolder)  
  80.   
  81. #Define ItemView to retrive just 1000 Items  
  82. $fldIdHash = @{}  
  83. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)  
  84. $ivItemView.PropertySet = $psPropset   
  85. $fiItems = $null      
  86. do{      
  87.     $fiItems = $service.FindItems($JunkEmail.Id,$ivItemView)      
  88.     #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  89.     foreach($Item in $fiItems.Items){   
  90.         $rptobj = "" | Select DateTimeReceived,Subject,FilteredBy,OriginalFolder  
  91.         $propval = $null  
  92.         $rptobj.Subject = $Item.Subject  
  93.         $rptobj.DateTimeReceived = $Item.DateTimeReceived  
  94.         if($Item.TryGetProperty($PidLidSpamOriginalFolder,[ref]$propval)){  
  95.   
  96.             $fldName = ""  
  97.             $FolderEntryId = $null  
  98.             $FolderEntryId = [System.BitConverter]::ToString($propval).Replace("-","")  
  99.             if($fldIdHash.ContainsKey($FolderEntryId) -eq $false){  
  100.                     $aiItem = New-Object Microsoft.Exchange.WebServices.Data.AlternateId        
  101.                     $aiItem.Mailbox = $MailboxName        
  102.                     $aiItem.UniqueId = $FolderEntryId     
  103.                     $aiItem.Format = [Microsoft.Exchange.WebServices.Data.IdFormat]::HexEntryId;    
  104.                     $fldId = $null  
  105.                     $fldId = $service.ConvertId($aiItem, [Microsoft.Exchange.WebServices.Data.IdFormat]::EwsId)    
  106.                     $fld = $null  
  107.                     if($fldId -ne $null){  
  108.                         $orgID = new-object Microsoft.Exchange.WebServices.Data.FolderId($fldId.UniqueId)     
  109.                         $fld = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$orgID)  
  110.                         $fldIdHash.Add($FolderEntryId,$fld.DisplayName)  
  111.                         $fldName = $fld.DisplayName  
  112.                     }  
  113.                               
  114.             }  
  115.             else{  
  116.                 $fldName = $fldIdHash[$FolderEntryId]  
  117.             }  
  118.             $rptobj.FilteredBy = "Client"  
  119.             $rptobj.OriginalFolder = $fldName     
  120.         }  
  121.         else{  
  122.             $rptobj.FilteredBy = "Server"             
  123.         }     
  124.         $rptCollection += $rptobj  
  125.     }      
  126.     $ivItemView.Offset += $fiItems.Items.Count      
  127. }while($fiItems.MoreAvailable -eq $true)   
  128. $rptCollection | Export-Csv c:\temp\junkemailClientreport.csv -NoTypeInformation