Tuesday, March 05, 2013

Removing attachments of a specific type with EWS and Powershell

Sometimes particular attachments can create different issues for a number of different reasons so you might find you want to get rid of all those attachments without removing the messages they are attached to. If you find yourself in this situation then this is the sample for you.

Firstly to find the attachments of a specific type we use the following AQS query

System.Message.AttachmentContents:.pdf

This acts as a first level filter but it will give a few false positives so a second client level check of the actual Attachment file name is needed.

  1. foreach ($Attachment in $Item.Attachments)  
  2. {  
  3.              if($Attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment]){    
  4.         if($Attachment.Name.Contains(".pdf")){  
  5.  
  6.         }  
  7.              }    
  8. }  
The following script can be run in one of two modes , Report will just report on attachments that are found in a particular folder and Delete will delete attachments from messages within that folder. I've put a download of this script here the code itself looks like.

  1. $RunMode = Read-Host "Enter Mode for Script (Report or Delete)"  
  2. switch($RunMode){  
  3.     "Report" {$runokay = $true  
  4.               "Report Mode Detected"  
  5.             }  
  6.     "Delete" {$runokay = $true  
  7.              "Delete Mode Detected"  
  8.              }  
  9.     default {$runOkay = $false  
  10.              "Invalid Reponse you need to type Report or Delete"  
  11.              }  
  12. }  
  13. if($runokay){  
  14. ## Get the Mailbox to Access from the 1st commandline argument  
  15.   
  16. $MailboxName = (Read-Host "Enter mailbox to run it against(email address)" )  
  17.   
  18. $rptcollection = @()  
  19.   
  20. ## Load Managed API dll    
  21. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"    
  22. [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")   
  23. [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")   
  24.   
  25. ## Set Exchange Version    
  26. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  27.     
  28. ## Create Exchange Service Object    
  29. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  30.     
  31. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  32.     
  33. #Credentials Option 1 using UPN for the windows Account    
  34. $psCred = Get-Credential    
  35. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  36. $service.Credentials = $creds        
  37.     
  38. #Credentials Option 2    
  39. #service.UseDefaultCredentials = $true    
  40.     
  41. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  42.     
  43. ## Code From http://poshcode.org/624  
  44. ## Create a compilation environment  
  45. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  46. $Compiler=$Provider.CreateCompiler()  
  47. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  48. $Params.GenerateExecutable=$False  
  49. $Params.GenerateInMemory=$True  
  50. $Params.IncludeDebugInformation=$False  
  51. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  52.   
  53. $TASource=@' 
  54.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  55.     public class TrustAll : System.Net.ICertificatePolicy { 
  56.       public TrustAll() {  
  57.       } 
  58.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  59.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  60.         System.Net.WebRequest req, int problem) { 
  61.         return true; 
  62.       } 
  63.     } 
  64.   } 
  65. '@   
  66. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  67. $TAAssembly=$TAResults.CompiledAssembly  
  68.   
  69. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  70. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  71. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  72.   
  73. ## end code from http://poshcode.org/624  
  74.     
  75. ## 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    
  76.     
  77. #CAS URL Option 1 Autodiscover    
  78. $service.AutodiscoverUrl($MailboxName,{$true})    
  79. "Using CAS Server : " + $Service.url     
  80.      
  81. #CAS URL Option 2 Hardcoded    
  82.     
  83. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  84. #$service.Url = $uri      
  85.     
  86. ## Optional section for Exchange Impersonation    
  87.     
  88. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  89.   
  90. $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);    
  91. $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)    
  92. # Bind to the Contacts Folder  
  93.   
  94. $rfRootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderidcnt)  
  95.   
  96. #Define the FolderView used for Export should not be any larger then 1000 folders due to throttling    
  97. $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  98. #Deep Transval will ensure all folders in the search path are returned    
  99. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  100. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  101. $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);    
  102. #Add Properties to the  Property Set    
  103. $psPropertySet.Add($PR_Folder_Path);    
  104. $fvFolderView.PropertySet = $psPropertySet;    
  105. #The Search filter will exclude any Search Folders    
  106. $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")    
  107. $fiResult = $null    
  108. #  
  109.   
  110. $Treeinfo = @{}  
  111. $TNRoot = new-object System.Windows.Forms.TreeNode("Root")  
  112. $TNRoot.Name = "Mailbox"  
  113. $TNRoot.Text = "Mailbox - " + $MailboxName  
  114. #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox    
  115. do {    
  116.     $fiResult = $Service.FindFolders($folderidcnt,$sfSearchFilter,$fvFolderView)    
  117.     foreach($ffFolder in $fiResult.Folders){     
  118.         #Process folder here  
  119.         $TNChild = new-object System.Windows.Forms.TreeNode($ffFolder.DisplayName.ToString())  
  120.         $TNChild.Name = $ffFolder.DisplayName.ToString()  
  121.         $TNChild.Text = $ffFolder.DisplayName.ToString()  
  122.         $TNChild.tag = $ffFolder.Id.UniqueId.ToString()  
  123.         if ($ffFolder.ParentFolderId.UniqueId -eq $rfRootFolder.Id.UniqueId ){  
  124.             $ffFolder.DisplayName  
  125.             [void]$TNRoot.Nodes.Add($TNChild)   
  126.             $Treeinfo.Add($ffFolder.Id.UniqueId.ToString(),$TNChild)  
  127.         }  
  128.         else{  
  129.             $pfFolder = $Treeinfo[$ffFolder.ParentFolderId.UniqueId.ToString()]  
  130.             [void]$pfFolder.Nodes.Add($TNChild)  
  131.             if ($Treeinfo.ContainsKey($ffFolder.Id.UniqueId.ToString()) -eq $false){  
  132.                 $Treeinfo.Add($ffFolder.Id.UniqueId.ToString(),$TNChild)  
  133.             }  
  134.         }  
  135.     }   
  136.     $fvFolderView.Offset += $fiResult.Folders.Count  
  137. }while($fiResult.MoreAvailable -eq $true)    
  138. $Script:clickedFolder = $null  
  139. $objForm = New-Object System.Windows.Forms.Form   
  140. $objForm.Text = "Folder Select Form"  
  141. $objForm.Size = New-Object System.Drawing.Size(600,600)   
  142. $objForm.StartPosition = "CenterScreen"  
  143. $tvTreView1 = new-object System.Windows.Forms.TreeView  
  144. $tvTreView1.Location = new-object System.Drawing.Size(1,1)   
  145. $tvTreView1.add_DoubleClick({  
  146.     $Script:clickedFolder = $this.SelectedNode.tag  
  147.     $objForm.Close()  
  148. })  
  149. $tvTreView1.size = new-object System.Drawing.Size(580,580)   
  150. $tvTreView1.Anchor = "Top,left,Bottom"  
  151. [void]$tvTreView1.Nodes.Add($TNRoot)   
  152. $objForm.controls.add($tvTreView1)  
  153. $objForm.ShowDialog()  
  154.   
  155. $clickedfolderid = new-object Microsoft.Exchange.WebServices.Data.FolderId($Script:clickedFolder)   
  156. #Define Attachment Contet To Search for  
  157.   
  158. $AttachmentContent = ".pdf"  
  159. $AQSString = "System.Message.AttachmentContents:$AttachmentContent"  
  160.   
  161. #Define ItemView to retrive just 1000 Items      
  162. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)      
  163. $fiItems = $null      
  164. do{      
  165.     $fiItems = $service.FindItems($clickedfolderid,$AQSString,$ivItemView)      
  166.     #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  167.     foreach($Item in $fiItems.Items){    
  168.             $Item.Load()  
  169.               
  170.             $attachtoDelete = @()  
  171.             foreach ($Attachment in $Item.Attachments)  
  172.             {  
  173.                 if($Attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment]){    
  174.                     if($Attachment.Name.Contains(".pdf")){  
  175.                         if($RunMode -eq "Report"){  
  176.                             $rptObj = "" | Select DateTimeReceived,Subject,AttachmentName,Size  
  177.                             $rptObj.DateTimeReceived = $Item.DateTimeReceived  
  178.                             $rptObj.Subject = $Item.Subject  
  179.                             $rptObj.AttachmentName = $Attachment.Name                         
  180.                             $rptObj.Size = $Attachment.Size  
  181.                             $rptcollection += $rptObj  
  182.                         }  
  183.                         $Attachment.Name  
  184.                         if($RunMode -eq "Delete"){  
  185.                             $attachtoDelete += $Attachment  
  186.                         }  
  187.                     }  
  188.                 }    
  189.             }  
  190.             $updateItem = $false  
  191.             foreach($AttachmentToDelete in $attachtoDelete){  
  192.                 if($RunMode -eq "Delete"){  
  193.                     $Item.Attachments.Remove($AttachmentToDelete)  
  194.                     $updateItem = $true  
  195.                 }  
  196.             }  
  197.             if($updateItem){$Item.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverWrite)};  
  198.     }      
  199.     $ivItemView.Offset += $fiItems.Items.Count      
  200. }while($fiItems.MoreAvailable -eq $true)  
  201. if($RunMode -eq "Report"){  
  202.     $rptcollection | Export-Csv -Path c:\temp\$MailboxName-AttachmentReport.csv -NoTypeInformation  
  203. }  
  204.   
  205. }  





3 comments:

Terry Wilkins said...

Firstly thank you very much for the script it has helped a lot, my only question is how could this be modified so that it would remove all attachments regardless of the type? Thank you!

Glen Scales said...

see http://msdn.microsoft.com/en-us/library/office/dd633682(v=exchg.80).aspx which has details of how to do each type of delete

Cheers
Glen

Anonymous said...

Hi Glen..Thanks for sharing the script. When I tried to Run it on an Exchange 2010 Ru 17 server, I m getting this error- The parameter queryString is only valid for Exchange Server version Exchange2010 or a later version. Am I Missing something..Please throw some light! Cheers Priya