为什么此Powershell脚本不删除已回复的所有Outlook电子邮件?

时间:2019-07-03 16:13:22

标签: powershell email outlook mapi new-object

我正在编写此脚本,以删除其他技术人员已经答复过的所有Exchange隔离电子邮件。

“有效”,但只是删除发现已回复的第一组电子邮件,即原始邮件和回复。

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

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

#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()
            }
        }
    }
}

当我第一次运行脚本时,该文件夹中有5封电子邮件,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

1 个答案:

答案 0 :(得分:1)

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

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