I am writing this script to delete any Exchange quarantined emails that have already been replied to by another technician.
It "works" but it only is deleting the first set of emails that it finds that have been replied to, the original plus the reply.
If I run the script a second time it then deletes the next set and so on.
I am not seeing why it is not looping through and deleting all of the emails that have been replied to instead of just the first set.
#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()
}
}
}
}
When I first ran the script the folder had five emails in it, 3 original quarantined emails and 2 replies. Here is the output on three runs which on each run it deleted only the first set of replies it found.
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
Never delete collection items in a "foreach" loop - you are modifying the collection, and that causes your code to skip at least some items. Use a down "for" loop (from Items.Count down to 1).
That being said, you should never be matching items explicitly in your own code - use Items.Find/FindNext
or Items.Restrict
. Let the store provider do the job.