1
votes

I am trying to write the sender/subject info of all the emails in my outlook inbox to a csv file and then move the emails to a subfolder of my inbox (called "After") using Powershell. The CSV file is created correctly with the email info, but only the first half + 1 emails are actually moved to the subfolder. Here is my code:

$olFolderInbox = 6;
$outlook = new-object -com outlook.application;
$mapi = $outlook.GetNameSpace("MAPI");
$inbox = $mapi.GetDefaultFolder($olFolderInbox);
$inbox.items|Select SenderEmailAddress,subject|Export-Csv C:\Scripts\Testing.csv -NoTypeInformation;
ForEach ($Item in $inbox.items){
    try{
        $Item.Move($inbox.Folders.Item("After")) | out-null;
    }catch{
        Write-Host "Failed to move item", $Item.Id.UniqueId;
    }
}

This is my first time using Powershell so any help is much appreciated!

1

1 Answers

0
votes

Move() changes the collection. Use a down "for" loop (from items.Count down to 1) instead of "foreach".