且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Powershell - Outlook将所有邮件标记为已读,然后删除

更新时间:2023-12-02 18:20:40

p>我建议使用 MailItem.Delete ()方法,而不是将事物移动到已删除邮件文件夹。从Delete()方法页面:


删除方法删除集合中的单个项目。删除所有
项目在文件夹的Items集合中,必须从文件夹中的最后一个项目开始删除每个项目
。例如,在项目
收集的文件夹 AllItems 中,如果
中有n个项目的文件夹,请开始删除项目在AllItems.Item (n),每次递减
索引,直到您删除 AllItems.Item(1)



删除方法将项目从包含文件夹移动到
已删除项目文件夹。如果包含的文件夹是已删除邮件
文件夹,则删除方法永久删除该项。


有了这个知识,我建议用以下代码替换ForEach循环:

  For($ i $($ emails.count-1); $ i -ge 0; $ i  - ){
$($ emails)[$ i] .Unread = $ false
$($ emails) [$ i] .delete()
}

我不明白你为什么为了枚举它来子表达集合,但是我从来没有能够在没有这样做的情况下指定记录。


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
}

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.