deleting email from mailbox and saving then to sql server

  • Hi

    I am working on script to save emails to database and delete them

    using example https://sqlnotesfromtheunderground.wordpress.com/2014/08/14/delete-emails-older-than-x-days-from-outlook-specific-folder-with-powershell/

    My delete code

    $MailBox = "SQLDBA@MYDomain.com"

    $Subfolder = "DBA_ALERTS"

    # Outlook Connection

    $Outlook = New-Object -ComObject Outlook.Application

    # Outlook folder to clean

    $EmailsInFolder = $Outlook.Session.Folders.Item($MailBox).Folders.Item($Subfolder).Items

    $OlderThenDays = 1

    $Today = get-date

    $counter = 0

    $EmailsInFolder.count

    foreach ($email in $EmailsInFolder)

    {

    $difference = New-TimeSpan -Start $email.SentOn -End $Today

    if ($difference.Days -ge $OlderThenDays)

    {

    $difference.Days

    $email.SentOn

    $email.Subject

    $email.Delete()

    $counter ++

    }

    }

    Write-Host $counter

    code is working but does not delete all selected email

    folder contain 500+ email meeting condition but foreach loop does not delete all selected emails at once

    I have to run code several times and each time it delete different amount of emails in decreasing order

    205,

    96,

    48

    15

    Do I have to call some other metod or set specific property in object in order to delete all selected emails at once ?

  • found it,

    look like you have to line them up before deleting http://stackoverflow.com/questions/24829011/powershell-outlook-mark-all-mails-as-read-then-delete

    and foreach loop can't be used if you modify collection

    what worked for me

    $OlderThenDays = 1

    $Today = get-date

    $i=($EmailsInFolder.count-1)

    For($i; $i -ge 0; $i--)

    {

    $difference = New-TimeSpan -Start $($EmailsInFolder)[$i].SentOn -End $Today

    if ($difference.Days -ge $OlderThenDays)

    {

    $($EmailsInFolder)[$i].SentOn

    $($EmailsInFolder)[$i].Subject

    $($EmailsInFolder)[$i].delete()

    }

    }

  • ebooklub (3/1/2016)


    ...foreach loop can't be used if you modify collection...

    Yep. Standard .NET limitation.

    Gaz

    -- Stop your grinnin' and drop your linen...they're everywhere!!!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply