user15229415
user15229415

Reputation: 55

Powershell - Moving outlook items from inbox to subfolder based on subject match

I am very new to powershell and am attempting to write a script that will move items from an outlook inbox into a 'Test' subfolder if the email subject matches a string. The script works in general however some emails are being skipped over.

The 1st time I run it, it moves 2 of the 4 emails that match the string. The 2nd time I run it, it moves the 3rd email. The 3rd time I run it, it moves the 4th email.

$olFolderInbox = 6
$outlook = new-object -com outlook.application;
$ns = $outlook.GetNameSpace("MAPI");
$inbox = $ns.GetDefaultFolder($olFolderInbox)
$targetfolder = $inbox.Folders | where-object { $_.name -eq "Test" }
$inbox.items | ForEach {
    $a=$_.subject -like 'Test*'
    if ($a) {[void]$_.Move($targetFolder)
    }
}

I cant figure out why it will not move all the emails whose subject matches the 'Test*' string on the 1st time I execute it.

Any help would be much appreciated! Thank you

Upvotes: 2

Views: 3884

Answers (1)

Mike L'Angelo
Mike L'Angelo

Reputation: 870

The only caveat I see when accessing Outlook Inbox via Outlook.Application is that Outlook is usually set up in cached mode. Empirically, emails outside Outlook cache are not enumerated.

Edit: It seems this behaviour is also documented - from Managing an Outlook mailbox with powershell

Experience shows that merely looping through all the messages in the Sent Items folder once isn’t enough; on a first loop, some items are handled but others aren’t touched. It may take three or four such loops to handle all the items that need handling. The number of loops probably depends on how many mail items are ready for copy-move operations and other factors in how Outlook interoperates with your computer. In any event, the solution is to use a Do-While structure to keep running the loop until all marked items have been properly managed.

Upvotes: 3

Related Questions