Updating User properties using GraphAPI

Remove Emails from a specific folder between specific date range using powershell script

Remove All Emails from a specific folder from user Mailbox, This script uses EWS so make sure you install Exchange web service 2.0 before using this script.
Copy the code and put that in a ps1 file, make sure to change the required attribute in script header.

########################################
#script Name = Delete_ALL_MSG_EWS-specific-folder.ps1
#Author = Sunil Chauhan
#Email= Sunilkms@gmail.com
#Ver = 1.0
# Deleting All Emails From a Specific Folder from a Mailbox.
# this script usese EWS to find and delete all the items from the user's defined folder.
#########################################
 
$user = "admin@LetsExchange.in"
$pass = "Password"
$Folder = "\Deleted Items" #replace with the folder Name
 
$toDate= get-date -Format MM/dd/yyyy 
#from date is hard coded in line no 87 to 01/01/2014 you can change it as per your search criteria.
 
#Web Service Path
$EWSServicePath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
Import-Module $EWSServicePath
$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
 
#for exchange 10 uncomment the below lines
#$ExchVer = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1
#$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($exchver) 
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList $user, $pass
 
#Setting up EWS URL
$EWSurl = "https://outlook.office365.com/EWS/Exchange.asmx"
$Service.URL = $EWSurl
 
# Defining Itemview depth
$ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(10000) 
$MailboxRootid = new-object  Microsoft.Exchange.WebServices.Data.FolderId `
([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$user)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$MailboxRootid)
 
# Get Folder ID from Path
Function GetFolder()
        {
        # Return a reference to a folder specified by path
        $RootFolder, $FolderPath = $args[0];
        $Folder = $RootFolder;
        if ($FolderPath -ne '\')
            {
             $PathElements = $FolderPath -split '\\';
             For ($i=0; $i -lt $PathElements.Count; $i++)
                  {
                   if ($PathElements[$i])
                       {
                       $View=New-Object  Microsoft.Exchange.WebServices.Data.FolderView(2,0);
                       $View.Traversal=[Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
                       $View.PropertySet=[Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly;
                       $SearchFilter=New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $PathElements[$i]);
                       $FolderResults=$Folder.FindFolders($SearchFilter, $View);                                                                            
                       if ($FolderResults.TotalCount -ne 1)
                           {
                           # We have either none or more than one folder returned... Either way, we can't continue
                           $Folder = $null;
                           Write-Host "Failed to find " $PathElements[$i];
                           Write-Host "Requested folder path: " $FolderPath;
                           break;
                           }
                 $Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $FolderResults.Folders[0].Id)
                }
           }              
      $Folder;       
      }
 
 try {
      $FolderObject = GetFolder ($MailboxRoot, $folder)
      #Date from and To
      #$findItemResults = $FolderObject.FindItems("System.Message.DateReceived:01/01/2014..$todate",$ItemView)
      $findItemResults = $FolderObject.FindItems($ItemView)
      foreach ($item in $findItemResults.Items) {
      try {
          #Comment Below out to not delete
          [void]$item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)
          $Deleted ++
          #Uncomment below to list before deleting
          #Write-host $item.DateTimeReceived
          } 
          catch 
          {
           Write-warning "Unable to delete item, $($item.subject).  $($Error[0].Exception.Message)"
          }
    }                                              
    if ($Deleted -gt 0) 
        { Write-host "$Deleted mail items deleted from the Inbox." }                               
    } 
catch 
     { 
      Write-warning "Could not connect to Inbox.$($_.exception.message)" 
      }



 

Comments

  1. Hi Sunil, Thanks for sharing this script. I ran this script and it delete 1k emails successfully and after that it stops eventually with below error.
    Warning: unable to delete item, RE: I hope you can help!!. Exeption calling “Delete” with “1” argument(s): The request failed. The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
    999 mail items deleted from the inbox.


    it seems to be some exception handling related error. Could you suggest what exception we should apply in code and at what line so that it will not fail.

    ReplyDelete
    Replies
    1. seems some throttling related issue, please try using impersonation account, I will share the new script for that which can be used with admin account to delete emails from any account.

      Delete

Post a Comment