Script to delete Outlook messages is not deleting all messages
<p>I am trying to delete messages in Outlook based on a specific tag in the email header.  Specifically, if "X-ZANTAZ-RECIP" is in the header multiple times, I want to keep the message.  If it is only in the header once, I want to delete the message.  This is part of an archive project I am working on.</p>

<p>I have scripts in vba and in powershell.  Both seem to work but I have to run it 5 time before it deletes all of the messages with only a single occurrence of this header tag.  The sample set I am working on contains ~70,000 messages.  First pass deletes ~24,000.  Second pass ~11,000.  Third pass ~3000...</p>

<p>Any ideas on why this would not be deleting all of the applicable messages on the first pass?</p>

<p>Powershell:</p>

<pre><code>$outlook = New-Object -ComObject 'Outlook.Application'
$currentFolder = ($outlook.ActiveExplorer()).CurrentFolder.Items
Foreach ($objemail in $currentFolder){
    $objheader = $objemail.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")
    $objoccurances = ([regex]::Matches($objheader, "X-ZANTAZ-RECIP" )).count
    If ($objoccurances -lt 2){
        $objemail.Delete()
        }
    Write-Host $objoccurances
    }
</code></pre>

<p>VBA:</p>

<pre><code>Sub DeleteMessages()
    Dim olItem As Outlook.MailItem, olMsg As Outlook.MailItem
    Dim strheader As String
    Dim output As String
    Dim CountOccurrences As Long

    For Each olItem In Application.ActiveExplorer.CurrentFolder.Items 'Application.ActiveExplorer.Selection
        strheader = GetInetHeaders(olItem)

    Next

    Set olMsg = Nothing
    MsgBox "finished"
End Sub

Function GetInetHeaders(olkMsg As Outlook.MailItem) As String
    Const PR_TRANSPORT_MESSAGE_HEADERS = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"
    Dim olkPA As Outlook.PropertyAccessor
    Set olkPA = olkMsg.PropertyAccessor
    GetInetHeaders = olkPA.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS)
    CountOccurrences = UBound(Split(GetInetHeaders, "X-ZANTAZ-RECIP"))
    If CountOccurrences &lt; 2 Then
        olkMsg.Delete
    End If
    Set olkPA = Nothing
End Function
</code></pre>