I’m trying to run the script below and it works fine.
The issue is that I want to only search the inbox and subfolders of the inbox, and exclude the sent folder is it possible?
Ultimately the intention is that I wish to delete all emails that users send to the entire workplace distribution list, that are over a month old. But not delete the original email that was sent.
I am new to scripting, and I have tried to get this working using EWS FindItems however the problem I encountered there is that I could figure out how to search through subfolders of inbox.
Unfortunately you cannot do this with Search-Mailbox. To do this with EWS you could try the following. This will enumerate all folders in a mailbox excluding Sent items. It should then output the emails that match your query and move them to the Deleted Items folder.
$ResultSize = 1000
$view = New-Object Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList $ResultSize
$SearchQuery = "" #Put you AQS query here i.e. Subject:Hello
$Response | ForEach-Object {
#Define which properties we want to retrieve from each message
$propertyset = New-Object Microsoft.Exchange.WebServices.Data.PropertySet ([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)
$view.PropertySet = $propertyset
#Use FindItems method for the specified folder, AQS query and number of messages
$items = $service.FindItems($_.id,$SearchQuery,$view)
#Loop through each message returned by FindItems
$items | ForEach-Object {
$emailProps = New-Object Microsoft.Exchange.WebServices.Data.PropertySet ([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$emailProps.RequestedBodyType = "Text"
$email = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($service, $_.Id, $emailProps)
#Create a custom object that returns the desired message properties
New-Object PSObject -Property @{
Subject = $email.Subject
From = $email.Sender.Name
To = $email.DisplayTo
Sent = $email.DateTimeSent
Mailbox = $Mailbox
IsRead = $email.IsRead
}
$_.Delete('MoveToDeletedItems')
}