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

 Remove emails from a specific folder between specific date range from user Mailbox.

As we are going to use the EWS make sure you met all the prerequisites before you plan to run this script.
  • Admin account should have application impersonation rights to run this script, you can follow this msdn post to setup the permissions.
  • Install EWS managed API on system where you plan to run the script from, if API is not installed, download the same from here
Copy the code and put that in a ps1 file, make sure to change the required attribute in script header.

Note: you can add either hard code admin credentials into PowerShell script or add them to powershell Session in ($cred) Array , this script will fetch the cred automatically from $cred Array by default, if now provided.

script.ps1 -AdminUser "AdminID" -Pass "Password" -Folder "Folder" -FromDate "03/01/2017" -ToDate "03/30/2017"

you can also report what emails this script will delete before you run this script, use -Report:$true  Switch, by default script run in Del Mode

script.ps1 -AdminUser "AdminID" -Pass "Password" -Folder "Folder" -FromDate "03/01/2017" -ToDate "03/30/2017" -Report:$true



#######################################################################################
#Author = Sunil Chauhan
#Email= Sunilkms@gmail.com
#Ver =https://sunil-chauhan.Blogspot.com
#Deleting Emails From a Specific Folder between specfic dates.#
########################################################################################

param (
$Adminuser=$cred.UserName,
$Pass=$cred.GetNetworkCredential().password,
$Folder="Deleted Items",
$ToDate="03/10/2017", #DATE Format MM/DD/YYYY
$FromDate="03/09/2017", #DATE Format MM/DD/YYYY
$Items=1000 ,
$MailboxToImpersonate="sunil.chauhan@xyz.com",
$Report
)

#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
$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 $Adminuser, $pass

#Setting up EWS URL
$EWSurl = "https://outlook.office365.com/EWS/Exchange.asmx"
$Service.URL = $EWSurl

$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId `
([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SMTPAddress,$MailboxToImpersonate);

# Defining Itemview depth
$ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView($items)
$MailboxRootid = new-object Microsoft.Exchange.WebServices.Data.FolderId `
([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxToImpersonate)
$MailboxRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$MailboxRootid)

# Get Folder ID from Path

$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,$Folder);
$FolderResults=$MailboxRoot.FindFolders($SearchFilter, $View);
$findItemResults = $FolderResults.FindItems("System.Message.DateReceived:$fromDate..$todate",$ItemView)

$Deleted=0
if ($report)
{
if ($findItemResults)
{
Write-Host "Folder:"$SearchFilter.value
Write-Host "Total Item Found:" $findItemResults.count -NoNewline
Write-Host " Between" $fromDate "and" $toDate
$findItemResults | Select Subject,DateTimeReceived,Sender
}
}
else {
Write-Host "Folder:"$SearchFilter.value
Write-Host "Total Item Found:" $findItemResults.count -NoNewline
Write-Host " Between" $fromDate "and" $toDate

foreach ($item in $findItemResults)
{
try {
$Deleted++
cls
""
Write-Host "Folder:"$SearchFilter.value
Write-Host "Total Item Found:" $findItemResults.count -NoNewline
Write-Host " Between" $fromDate "and" $toDate
""
Write-host "Deleting:"$Deleted
[void]$item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete)
}
catch
{
Write-host "Unable to delete item:$($item.subject)"
Write-host "Error:$($Error[0].Exception.Message)"
}
}
if ($Deleted -gt 0) { Write-host "$Deleted email items has been deleted from the Mailbox." }
}

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