问题
having some problems trying to figure this one out. For some reason my script is not working as it should.
It should mark all mails in inbox folder as read and then delete them. However, when the script runs it only delete's half of the .count $emails show...
How to solve this, am I doing something wrong?
$outlook = new-object -comobject outlook.application
#Define folders
$namespace = $outlook.GetNameSpace("MAPI")
$pst = $namespace.Stores
$pstRoot = $pst.GetRootFolder()
$pstFolders = $pstRoot.Folders
#$personal = $pstFolders.Items("ARCHIVE") ##Not working, sadly.
$DefaultFolder = $namespace.GetDefaultFolder(6)
$InboxFolders = $DefaultFolder.Folders
$DeletedItems = $namespace.GetDefaultFolder(3)
$Emails = $DefaultFolder.Items
Foreach ($Email in $Emails) {
#Define folders
$Email.UnRead = $false
$Email.Move($DeletedItems) | out-null
continue
}
回答1:
I would suggest using the MailItem.Delete() method instead of moving things to the Deleted Items folder. From the Delete() method page:
The Delete method deletes a single item in a collection. To delete all items in the Items collection of a folder, you must delete each item starting with the last item in the folder. For example, in the items collection of a folder, AllItems, if there are n number of items in the folder, start deleting the item at AllItems.Item(n), decrementing the index each time until you delete AllItems.Item(1).
The Delete method moves the item from the containing folder to the Deleted Items folder. If the containing folder is the Deleted Items folder, the Delete method removes the item permanently.
With that knowledge I would suggest replacing your ForEach loop with the following:
For($i=($emails.count-1);$i -ge 0;$i--){
$($emails)[$i].Unread = $false
$($emails)[$i].delete()
}
I don't understand why you have to sub-expression the collection in order to enumerate it, but I've never been able to specify a record without doing that.
回答2:
Do not use "foreach" loop since you are modifying the number of items in the collection. Use a loop from Items.Count down to 1.
来源:https://stackoverflow.com/questions/24829011/powershell-outlook-mark-all-mails-as-read-then-delete