[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

PowerShell script for deleting old messages from specific folder Exchnage 2010

Posted on 2014-08-26
8
Medium Priority
?
4,955 Views
Last Modified: 2014-09-11
I am looking for a powershell script to deleted messages from a user's mailbox that targets messages older than 'x' number of days within a specific folder (inbox or deleted items). Can somebody assist with the script?
0
Comment
Question by:GR JN
  • 3
  • 3
  • 2
8 Comments
 
LVL 29

Assisted Solution

by:becraig
becraig earned 1000 total points
ID: 40286384
You can look into outlook retention policy for an easier to manage option:
If you use Exchange 2010, see below: Retention Policy

http://technet.microsoft.com/en-us/library/dd297955.aspx

http://technet.microsoft.com/en-us/library/bb123548.aspx

Also a script reprinted from:
http://social.technet.microsoft.com/Forums/exchange/en-US/581ea5df-0e65-47ea-8efd-aa67e27c0320/powershell-script-that-deletes-email-older-than-x-days-with-a-specific-subject-line-exchange?forum=exchange2010


[DateTime]$Today = (Get-Date).adddays(-30)
Search-Mailbox -Identity "Starr, Ringo" -SearchQuery "Received:> $($Today) and Received:(Today) and subject:Strawberry" -DeleteContent -force

Open in new window

0
 

Author Comment

by:GR JN
ID: 40286391
Thanks. How would I target or specify a specific folder?

We do not want to use a retention policy as a lot of these requests are one offs.
0
 
LVL 67

Accepted Solution

by:
sirbounty earned 1000 total points
ID: 40286400
You'll probably want to have a look at EWS: http://msdn.microsoft.com/en-us/library/office/dd877045(v=exchg.140).aspx

And here's a sample script that I have used for similar purposes:

[string]$ModuleDllPath = "$env:SystemDrive\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
[string]$ServerVersion = 'Exchange2010_SP1'
[string]$script:AccountMailbox ='Someone@Somewhere.com'
[int]$DeleteDayAge=365
[void][ValidateRange(0,86400000)][int] $Timeout
[ValidatePattern('^https?://[^/]*/ews/exchange.asmx$|^AutoDetect$')][Alias('Url')][string] $EwsUrl = "AutoDetect"

try {
    if (-not (get-module -Name:Microsoft.Exchange.WebServices)) {
        try {
            Import-Module -Name $ModuleDllPath -ErrorAction:Stop
        } catch {
            throw "$_`nPlease install EWS before implementing this tool"
        }
    }
    if ($ServerVersion -eq 'AutoDetect') {
        $ExchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
    } else {
        $ExchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ServerVersion)
    }
    if ( $Timeout ) {
        if ( $Timeout -lt $ExchangeService.Timeout ) {
            Write-Warning "Timeout < builtin default value. ($Timeout<$($ExchangeService.Timeout)) Define larger value if the function does not respond"
        }
        $ExchangeService.Timeout = $Timeout
    }
    if ( $EwsUrl -eq 'AutoDetect' ) {
        $ExchangeService.AutodiscoverUrl($AccountMailbox)
    } else {
        $ExchangeService.Url = New-Object Uri($EwsUrl)
    }

    $FolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
    $ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
    $wkfn = [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]
    $TargetFolder = New-Object Microsoft.Exchange.WebServices.Data.FolderId($wkfn::Inbox,$AccountMailbox)
    $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ExchangeService,$TargetFolder) 
    $SearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$Inbox)
    $findItemResults = $Inbox.FindItems($ItemView)
    do {
        foreach ($item in $findItemResults.Items) {
            if ([math]::Abs((New-TimeSpan -Start $item.DateTimeReceived -End (get-date)).Days) -gt $DeleteDayAge) {
                try {
                    [void]$item.Delete()
                    $Deleted ++
                } catch {
                    Write-warnging "Unable to delete item, $($item.subject).  $($Error[0].Exception.Message)"
                }
            }
        }
    } while ($findItemResults.MoreAvailable)
    if ($Deleted -gt 0) { Write-host "$Deleted mail items deleted from the Inbox." }
} catch {
    Write-warning "Could not connect to Inbox.  $( $_.exception.message )"
}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:GR JN
ID: 40286406
Thanks but is there a way to specify a specific subfolder in the user mailbox?
0
 
LVL 67

Expert Comment

by:sirbounty
ID: 40286430
If that was to me, yes, absolutely.
I use this to cleanup a subfolder of the inbox...

I just use this for our 'Archive Folder'
$SearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,'Archive Folder')

Open in new window

0
 
LVL 29

Expert Comment

by:becraig
ID: 40286431
For that specific feature EWS will also accomplish this using folder operations:
Folder Operations

The Folder operations provide access to folders in the Exchange data store. A client application can create, update, delete, copy, find, get, and move folders that are associated with a mailbox user. Folders are used to gain access to items in the store, and provide a reference container for items in the store.

Same link as provided above from Sir Bounty
 http://msdn.microsoft.com/en-us/library/office/dd877045(v=exchg.140).aspx
0
 

Author Comment

by:GR JN
ID: 40286435
There is now way to specify a folder just using the Exchange Management shell? This below script would be ideal if I can specify the folder

[DateTime]$Today = (Get-Date).adddays(-30)
Search-Mailbox -Identity "Starr, Ringo" -SearchQuery "Received:> $($Today) and Received:(Today) and subject:Strawberry" -DeleteContent -force
0
 
LVL 29

Expert Comment

by:becraig
ID: 40286444
Sadly no :~(

The search mailbox cmdlet will take subject keywords etc but you are not able to specify the subfolder.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Steps to fix “Unable to mount database. (hr=0x80004005, ec=1108)”.
Exchange administrators are always vigilant about Exchange crashes and disasters that are possible any time. It is quite essential to identify the symptoms of a possible Exchange issue and be prepared with a proper recovery plan. There are multiple…
To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question