Using powershell to move emails from one folder to another

417 views Asked by At

I am trying to write a script to move emails from one folder to another in the same mailbox using Powershell and the ExchangeOnlineManagement module. From what I understand, the following should work after importing exchange module and signing in with

Connect-ExchangeOnline --UserPrincpleName "[email protected]"

$mailboxName = "[email protected]"
$sourceFolder = "test"
$targetFolder = "test2"

# Initialize counters for success and failure
$successCount = 0
$failureCount = 0

try {
    # Get all emails from the source folder
    $emails = Get-MailboxFolderStatistics -Identity $mailboxName | Where-Object { $_.Name -eq $sourceFolder } | Get-MailboxFolderStatistics | Where-Object { $_.ItemType -eq "Message" }

    # Iterate through each email and move it to the target folder
    foreach ($email in $emails) {
        try {
            Move-Item -Identity "$mailboxName\$sourceFolder\$($email.EntryID)" -TargetFolder "$mailboxName\$targetFolder"
            $successCount++
        } catch {
            $failureCount++
            Write-Host "Failed to move email: $($email.Subject). Error: $_"
        }
    }

    Write-Host "Successfully moved $successCount emails from $sourceFolder to $targetFolder for mailbox $mailboxName."
    Write-Host "Failed to move $failureCount emails."

} catch {
    Write-Host "Error moving emails for mailbox $mailboxName. Error Details: $_"
}

However I am getting the following error:

Get-MailboxFolderStatistics: Ex3F6FA7|Microsoft.Exchange.Management.Tasks.MailboxFolderStatisticsException|Unable to retrieve mailbox folder statistics for mailbox [email protected]\test. Failure: Couldn't find '[email protected]\test' as a recipient.

Any help you may be able to provide would be appreciated.

0

There are 0 answers