0

我正在编写此脚本以删除已由其他技术人员回复的任何 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
4

1 回答 1

1

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

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

于 2019-07-03T16:58:31.513 回答