Search code examples
powershellexchange-server

PowerShell - Find Oldest Email


I am stuck, I am trying to find the oldest "EMAIL" in a person's mailbox, but I don't know what else to try. I think I need to add the ContainerClass -eq "IPF.Note" somewhere, but I am not sure where.

The following script works, but it finds the oldest ITEM, which in my case it is a contact. I want to look at each container (Email, Chats, Calendar, Contacts) separately, but for this script, I just want to know the oldest email.

Thank you

Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity USERID | 
    Where OldestItemReceivedDate -ne $null | 
    Sort OldestItemReceivedDate | 
    Select -First 1 OldestItemReceivedDate

Solution

  • You can filter what you have by item type, but I would do it after getting the statistics so you only have to query exchange once:

    # Get the folder statistics for all folders
    $stats = Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity $USERID
    
    # Get the oldest email. Can re-use $stats for the other item types
    $OldestEmail = $stats |
      Where-Object {$_.OldestItemReceivedDate -and $_.ContainerClass -eq 'IPF.Note'} |
      Sort-Object OldestItemReceivedDate |
      Select-Object ContainerClass,OldestItemReceivedDate,FolderPath -First 1
    
    # Outputs
    ContainerClass OldestItemReceivedDate FolderPath
    -------------- ---------------------- ----------
    IPF.Note       2/8/2016 2:07:50 PM    /Inbox    
    

    You are correct that the mailbox folder statistics command does not search recoverable items by default. It also does not search the mailbox archive unless you specify -Archive. If you need these, you'll have to do additional searches:

    # Get recoverable items:
    Get-MailboxFolderStatistics -Identity $USERID -FolderScope 'RecoverableItems' -IncludeOldestAndNewestItems |
      Where-Object OldestItemReceivedDate |
      Sort-Object  OldestItemReceivedDate |
      Select-Object ContainerClass,OldestItemReceivedDate,FolderPath -First 1
    
    # Note that deleted item containers do not have an item type!
    ContainerClass OldestItemReceivedDate FolderPath       
    -------------- ---------------------- ----------       
                   2/5/2016 3:41:33 PM    /Deletions