Tuesday, 9 January 2018

Search Office 365 Mailbox : Delete, Copy and Move Messages using PowerShell

In this post I am going to share PowerShell script to search mailbox and delete, copy and move searched messages from one mailbox to another mailbox. We can use the exchange powershell cmdlet Search-Mailbox to search a mailbox and copy the results to a specified target mailbox and this cmdlet is available for both Exchange On-Premises and Exchange Online environment.

Before proceed, first we need to connect Exchange Online powershel module by running below commands:
$o365Cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $o365Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session

Summary:


Delete searched messages from mailbox

To delete messages we need to use DeleteContent switch, to use the DeleteContent switch you have to be assigned the Mailbox Import Export management role. By default, this role isn't assigned to any role group. Typically, you assign a role to a built-in or custom role group. Or you can assign a role to a user, or a universal security group. The below example add the role to the Organization Management role group:
New-ManagementRoleAssignment -Name "Import_Export_Organization_Management" -SecurityGroup "Organization Management" -Role "Mailbox Import Export"
Note: You have to create a new Exchange Online PowerShell session to get new role permissions.

This example searches Alex Wilber's mailbox for messages that contain the phrase "test message" in the subject and deletes the messages from the source mailbox.
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"test message" } -DeleteContent

Copy messages between mailboxes

This example searches Alex Wilber's mailbox for messages that contain the subject "sales report" in the subject and copy the result messages to Allan Deyoung's mailbox in the target folder "Sales".
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"sales report" } -TargetMailbox "Allan Deyoung" -TargetFolder "Sales"

Move messages from source mailbox to target mailbox

Move operation is nothing but the copy action along with removing messages from source mailbox. This example search and move messages from Alex Wilber's mailbox to Allan Deyoung's mailbox.
Search-Mailbox -Identity "Alex Wilber" -SearchQuery {Subject:"sales report" } -TargetMailbox "Allan Deyoung" -TargetFolder "Sales" -DeleteContent

Advertisements
Advertisements

No comments:

Post a Comment