PowerShell script for deleting old messages from specific folder Exchnage 2010

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?
Rammy CharlesSales EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

becraigCommented:
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
Rammy CharlesSales EngineerAuthor Commented:
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
sirbountyCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Rammy CharlesSales EngineerAuthor Commented:
Thanks but is there a way to specify a specific subfolder in the user mailbox?
0
sirbountyCommented:
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
becraigCommented:
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
Rammy CharlesSales EngineerAuthor Commented:
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
becraigCommented:
Sadly no :~(

The search mailbox cmdlet will take subject keywords etc but you are not able to specify the subfolder.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.