Wednesday, September 25, 2013

Junk Email SCL report using EWS and Powershell

Dealing with Junk Email is kind of like doing the dishes, it's dirty work but somebodies got to do it. While Spam filters are improving we know by the constant updates these filters require its an invisible war that's always going on. Also software being what it is, things don't always go to plan like this http://support.microsoft.com/kb/2885002/en-us

So it can be good to check in on what's happening in your User's JunkEmail folders from time to time and EWS is great for doing this so.

The following EWS script scans all the messages in the JunkEmail folder of a Mailbox (or Mailboxes) and looks at the SCL value of each of the Messages which is held in the

PidTagContentFilterSpamConfidenceLevel property

And also looks at the

PidLidSpamOriginalFolder property which contains the original folder a Message was moved from, which only gets set when the Outlook Junk Email Filter takes an action on a message vs the Server Side action (where this properties doesn't get set)

This script produces a report that shows the number of message for each SCL levels, total number of messages in the JunkEmail folder and the number of Messages move just by just Outlook Filter eg.


To run the script you need to feed it with a CSV with the mailbox you want to run it against something like

SmtpAddress
user@domain.com
user2@domain.com

Then use .\sclReport.pst .\users.csv

I've put a download of the script here

The script looks like

  1. $Script:rptCollection = @()    
  2.   
  3. ## Load Managed API dll    
  4. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  5.     
  6. ## Set Exchange Version    
  7. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  8.     
  9. ## Create Exchange Service Object    
  10. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  11.     
  12. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  13.     
  14. #Credentials Option 1 using UPN for the windows Account    
  15. $psCred = Get-Credential    
  16. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  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. ## Code From http://poshcode.org/624  
  25. ## Create a compilation environment  
  26. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  27. $Compiler=$Provider.CreateCompiler()  
  28. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  29. $Params.GenerateExecutable=$False  
  30. $Params.GenerateInMemory=$True  
  31. $Params.IncludeDebugInformation=$False  
  32. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  33.   
  34. $TASource=@' 
  35.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  36.     public class TrustAll : System.Net.ICertificatePolicy { 
  37.       public TrustAll() {  
  38.       } 
  39.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  40.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  41.         System.Net.WebRequest req, int problem) { 
  42.         return true; 
  43.       } 
  44.     } 
  45.   } 
  46. '@   
  47. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  48. $TAAssembly=$TAResults.CompiledAssembly  
  49.   
  50. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  51. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  52. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  53.   
  54. ## end code from http://poshcode.org/624  
  55.     
  56. ## 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    
  57.     
  58. #CAS URL Option 2 Hardcoded    
  59.     
  60. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  61. #$service.Url = $uri      
  62.     
  63. ## Optional section for Exchange Impersonation    
  64.     
  65. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $SmtpAddress)   
  66.   
  67. function Process-Mailbox{  
  68.     param (  
  69.             $SmtpAddress = "$( throw 'SMTPAddress is a mandatory Parameter' )"  
  70.           )  
  71.     process{  
  72.         Write-Host ("Processing Mailbox : " + $SmtpAddress)  
  73.         $rptObj = "" | select MailboxName,TotalItems,MovedByOutlook,NoSCL,SCLneg1,SCL0,SCL1,SCL2,SCL3,SCL4,SCL5,SCL6,SCL7,SCL8,SCL9  
  74.         $rptObj.MovedByOutlook = 0  
  75.         $rptObj.NoSCL = 0  
  76.         $rptObj.SCLneg1 = 0  
  77.         $rptObj.SCL0 = 0  
  78.         $rptObj.SCL1 = 0  
  79.         $rptObj.SCL2 = 0  
  80.         $rptObj.SCL3 = 0  
  81.         $rptObj.SCL4 = 0  
  82.         $rptObj.SCL5 = 0  
  83.         $rptObj.SCL6 = 0  
  84.         $rptObj.SCL7 = 0  
  85.         $rptObj.SCL8 = 0  
  86.         $rptObj.SCL9 = 0  
  87.         # Bind to the Junk Email Folder  
  88.         $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$SmtpAddress)     
  89.         $JunkEmail = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  90.         $rptObj.MailboxName = $SmtpAddress  
  91.         $rptObj.TotalItems = $JunkEmail.TotalCount  
  92.         $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
  93.         $PidTagContentFilterSpamConfidenceLevel = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x4076, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  94.         $PidLidSpamOriginalFolder = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,0x859C, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  95.         $psPropset.Add($PidTagContentFilterSpamConfidenceLevel)  
  96.         $psPropset.Add($PidLidSpamOriginalFolder)  
  97.         #Define ItemView to retrive just 1000 Items      
  98.         $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  99.         $ivItemView.PropertySet = $psPropset  
  100.         $fiItems = $null      
  101.         do{      
  102.             $fiItems = $service.FindItems($JunkEmail.Id,$ivItemView)      
  103.             #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  104.             foreach($Item in $fiItems.Items){  
  105.                 $OrigFldVal = $null  
  106.                 if($Item.TryGetProperty($PidLidSpamOriginalFolder,[ref]$OrigFldVal)){  
  107.                     $rptObj.MovedByOutlook +=1  
  108.                 }  
  109.                 $SCLVal = $null;  
  110.                 if($Item.TryGetProperty($PidTagContentFilterSpamConfidenceLevel,[ref]$SCLVal)){  
  111.                     switch($SCLVal){  
  112.                         {$_ -lt 0}{$rptObj.SCLneg1 += 1}  
  113.                         0 { $rptObj.SCL0 += 1 }  
  114.                         1 { $rptObj.SCL1 += 1 }  
  115.                         2 { $rptObj.SCL2 += 1 }  
  116.                         3 { $rptObj.SCL3 += 1 }               
  117.                         4 { $rptObj.SCL4 += 1 }  
  118.                         5 { $rptObj.SCL5 += 1 }  
  119.                         6 { $rptObj.SCL6 += 1 }  
  120.                         7 { $rptObj.SCL7 += 1 }  
  121.                         8 { $rptObj.SCL8 += 1 }               
  122.                         9 { $rptObj.SCL9 += 1 }  
  123.                     }  
  124.                 }  
  125.                 else{  
  126.                     $rptObj.NoSCL +=1  
  127.                 }                          
  128.             }      
  129.             $ivItemView.Offset += $fiItems.Items.Count      
  130.         }while($fiItems.MoreAvailable -eq $true)   
  131.         $Script:rptCollection += $rptObj  
  132.     }  
  133. }  
  134.   
  135. Import-Csv -Path $args[0] | ForEach-Object{  
  136.     if($service.url -eq $null){  
  137.         $service.AutodiscoverUrl($_.SmtpAddress,{$true})   
  138.         "Using CAS Server : " + $Service.url   
  139.     }  
  140.     Try{  
  141.         Process-Mailbox -SmtpAddress $_.SmtpAddress  
  142.     }  
  143.     catch{  
  144.         LogWrite("Error processing Mailbox : " + $_.SmtpAddress + $_.Exception.Message.ToString())  
  145.     }  
  146. }  
  147. $Script:rptCollection | Export-Csv -NoTypeInformation -Path c:\temp\sclReport.csv  


1 comment:

DevaconTV said...

I have a problem with your script under Exchange 2016. Can you help me?

Import-Csv : Das Argument für den Parameter "Path" kann nicht überprüft werden. Das Argument ist NULL oder leer. Geben
Sie ein Argument an, das nicht NULL oder leer ist, und führen Sie den Befehl erneut aus.
In C:\Download\Report_SCL\scl_report.ps1:135 Zeichen:18
+ Import-Csv -Path $args[0] | ForEach-Object{
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Import-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportCsvCommand