Powershell - Outlook Mark all mails as read then delete

前提是你 提交于 2019-12-07 19:22:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!