Note: A completely rewritten and enhanced version of this script can be found here.
Manipulation of mailbox items is not something that is really available using Exchange cmdlets – understandably, as Exchange PowerShell is for administration of the Exchange environment rather than manipulation of mailboxes themselves. Of course, PowerShell itself offers all the features needed to be able to write a script to anything that is possible using EWS, so with a little EWS and PowerShell knowledge we can manipulate pretty much anything.
In a migration scenario recently, a customer found that due to the legacy system being migrated, items were not in the expected folder once a mailbox had been moved to Exchange 2010. In this case, the sent items were actually in a subfolder of the Sent Items folder. So, the question was asked whether we can give a sample script that shows how to move all these items from the subfolder into the Sent Items folder.
Attached is a script that does exactly this. In fact, it will work for any folder, and can optionally delete the source folder on completion. If delete is requested, the folder will only actually be deleted if it is empty, so in the event that an item failed to move, nothing will be lost. The script accepts parameters so can be combined with other PowerShell features to process many mailboxes in a batch job. It was tested against Office 365 and on-premises Exchange. The script is attached, and the parameters are detailed below:
MoveItems -Mailbox <string>
[-Username <string> -Password <string> [-Domain <string>]]
-Mailbox : Mailbox SMTP email address
-SourceFolder : Full path to source folder in the mailbox (items are moved from this folder)
-TargetFolder : Full path to target folder in the mailbox (items are moved to this folder)
-ProcessSubfolders : If true, subfolders of the source folder will also be processed (default is false)
-DeleteSourceFolder : If true, the source folder will be deleted once items moved (so long as it is empty)
-Username : Username for the account being used to connect to EWS (if not specified, current user is assumed)
-Password : Password for the specified user (required if username specified)
-Domain : If specified, used for authentication (not required even if username specified)
-Impersonate : Set to $true to use impersonation.
-EwsUrl : Forces a particular EWS URl (otherwise autodiscover is used, which is recommended)
-IgnoreSSLCertificate : If $true, then any SSL errors will be ignored
-EWSManagedApiDLLFilePath : Full and path to the DLL for EWS Managed API (if not specified, default path for v1.2 is used)
-LogVerbose: Show detailed output
PS C:\powershell> .\moveitems.ps1 -Mailbox Administrator@exch2k10sp2.local -SourceFolder “Inbox\Test” -TargetFolder “\” -ignoresslcertificate $true -processsubfolders $true
The above will copy items from the folder Inbox\Test into the root folder, and process subfolders (e.g. Inbox\Test\Inbox items will be moved into the user’s main inbox).