Moving Emails

I have a script that almost works…when I run this the following happens…

If 4 emails present, it will move 2. If 2 emails present, it will move 1, and if 1 email present, then it will move the 1. So for 4 emails, the process needs run 3 times to clear the inbox down

I understand a loop etc starts at 0 but I’m not using an array, I’m merely using:

$Inbox.Items | ForEach-Object -Process { $_.Move($MoveTarget) }

Can anybody advise me why the email process in these numbers (4emails = 2moved, 2emails = 1moved) at least if I knew why then I might be able to resolve myself. I guess it’s something to do with the fact that I am moving emails that constitute a stack?

I have a solution whereby I repeat the above loop processing the emails within an outer loop i.e. a loop within a loop, until all emails have been processed but to me it’s inefficient so would like to resolve it.

Sounds like your list is dynamic. When you move the first one, the list changes, so you can’t reliably loop through it. Assuming you can index it, or use some method to retrieve the first item, you’ll want to use a while loop, moving the first object each loop until the count is 0. Pseudo code:

while ($dynlist.Count -gt 0) {
$dynlist[0].Move()
}

You could also loop backwards using an index, but there’s no guarantee some other process won’t change the contents.

Check out this thread. Basically, if you process the list backwards it corrects the behavior:

https://powershell.org/forums/topic/get-unread-mail-on-outlook-and-set-it-to-read/