为什么这个 powershell 脚本没有删除所有已回复的 Outlook 电子邮件?

Why is this powershell script not deleting all Outlook Emails That Have Been Replied To?

我正在编写此脚本以删除任何已被其他技术人员回复的 Exchange 合格运行电子邮件。

它 "works" 但它只是删除它发现已回复的第一组电子邮件,即原始邮件和回复邮件。

如果我第二次 运行 脚本,它会删除下一组,依此类推。

我不明白为什么它不遍历并删除所有已回复的电子邮件,而不仅仅是第一组。

#connect to outlooks
$outlook = new-object -comobject “Outlook.Application”
$mapi = $outlook.getnamespace(“mapi”)

#connect to outlook inbox
$inbox = $mapi.GetDefaultFolder(6)

#find the subfolder named Exchange Quarantined
$subfolder = $inbox.Folders | Where-Object {$_.Name -eq “Exchange Quarantined”}

#loop through emails and if someone already replied to the email then delete all emails with that users name in it
ForEach ($email in $subfolder.Items) {
    $subject = $email.Subject

    #Get the users name out of the subject line
    $user = $subject.Split("(")
    $name = $user[0] -replace ".*device that belongs to "
    $name = $name.Trim()
    Write-host $name
    if($subject -like "*RE: A device that belongs to*") {
        ForEach ($emailDelete in $subfolder.Items) {
            $subjectDelete = $emailDelete.Subject

            if($subjectDelete -like "*$name*") {
                Write-Host "Delete $subjectDelete"
                $emailDelete.Delete()
            }
        }
    }
}

当我第一次 运行 脚本时,该文件夹中有五封电子邮件,3 封原始合格运行电子邮件和 2 封回复。这是三个 运行 的输出,在每个 运行 上它只删除了它找到的第一组回复。

PS H:\> C:\Users\todd.welch\Downloads\Exchange Quarantined.ps1
Lan Fill
Adam Pac
Adam Pac
Delete A device that belongs to Adam Pac (adam.pac) has been quarantined. Exchange ActiveSync will be blocked until you take action.
Delete RE: A device that belongs to Adam Pac (adam.pac) has been quarantined. Exchange ActiveSync will be blocked until you take action.

PS H:\> C:\Users\todd.welch\Downloads\Exchange Quarantined.ps1
Lan Fill
Antonia Gonz
Antonia Gonz
Delete A device that belongs to Antonia Gonz (antonia.gonz) has been quarantined. Exchange ActiveSync will be blocked until you take action.
Delete RE: A device that belongs to Antonia Gonz (antonia.gonz) has been quarantined. Exchange ActiveSync will be blocked until you take action.

PS H:\> C:\Users\todd.welch\Downloads\Exchange Quarantined.ps1
Lan Fill

切勿在 "foreach" 循环中删除集合项 - 您正在修改集合,这会导致您的代码至少跳过某些项。使用向下 "for" 循环(从 Items.Count 向下到 1)。

也就是说,您永远不应该在自己的代码中显式匹配项目 - 使用 Items.Find/FindNextItems.Restrict。让商店提供商来完成这项工作。