This function is supposed to delete all items in the “Deleted Items” folder in Outlook (2013).
function Empty-DeletedItems {
$Outlook = New-Object -ComObject Outlook.Application
Foreach ($Folder in $Outlook.Session.Folders){
Foreach($MailFolder in $Folder.Folders ) {
if ($MailFolder.Name -eq "Deleted Items" -and $MailFolder.Items.Count -gt 0){
Foreach ($Item in $MailFolder.Items){
$item.Delete()
}
}
}
}
}
However, when I call it, only 5-7 items get deleted from the “Deleted Items” folder. I can run it 5-10 times and the folder eventually empties, but I’m curious why it’s not deleting every item in one run?
I’ve never had a lot of luck with that Outlook COM object, unfortunately. It’s old, and it’s not terribly well designed. The fact that you’re eventually able to get what you want is a small miracle ;).
The Outlook COM object can only access what you’ve got cached on your computer. Perhaps the deleted items is considered low priority so only the most recent few are loaded?
Try to get a count on the number of items this script can see in deleted items.
Instead of deleting each item I think there should be a method available on the deleted items folder object to “empty deleted items” (can’t recall it off the top of my head, sorry). Alternatively you could look at EWS (Exchange Web Services) and that will interact with the exchange server rather than trying to manipulate the (as Don said) old (and unreliable) Outlook COM object.