Search code examples
powershelloutlooketl

How to download an Outlook attachments based on specific file name within the 24 hrs?


I'm trying to download attachments within emails based on file name that have been received within the last 24 hour AND are the first match. The first match is in-case a second email with the same filename is received and needed to be output to the location. The files are received to the inbox typically once a day but there are times where it'll have to be handled via the 'latest received'. So wit that said, when there is a match, the code supposed to grab the files and put the first matched files to the location and then stop / terminate the script.

However, it doesn't seem to take the time factor into account at all. At this point my code finds the first matched two files based on the filename, and dumps them into the location. Then it keeps overwriting the files as it finds older files with the same name within the inbox.

In this latest build / attempt, I'm using $limit = (Get-Date).AddDays(-1) as well as -and ($_.CreationTime -lt $limit) in my code. I've tried a number of methods but nothing seems to work.

    $account = '[email protected]'
    $targetFolder = 'inbox'
    $f = $account.Folders | ? { $_.Name -match 'inbox'};
    $email = $f.Items|  Sort-Object ReceivedTime -Descending | Select-Object -First 1 
    $limit = (Get-Date).AddDays(-1)
    $filepath = "\\servername\home\blah\Documents\blah's emails"
    $ol = New-Object -comobject outlook.application
    $ns = $ol.GetNamespace('MAPI')
    $acct = $ns.Folders[$account]
$acct.Folders[$targetFolder].Items | foreach {
    if ($_.ReceivedTime -match $email -and ($_.CreationTime -eq $limit)) { 
            $_.attachments |
            foreach {
                Write-Host "attached file: ",$_.filename
                If ($_.filename -match 'BlahCompletions' -or $_.filename -match 'BlahCertifications'){
                    $_.saveasfile((Join-Path $filepath $_.FileName))
                } 
            } 
    }
}

Solution

  • You use CreationTime -eq $limit. -eq means equal. So it only works if the CreationTime is the exact same microsecond as $limit. What you are looking for is -gt (greater than) or -ge (greater or equal).

    The other problem is $_.ReceivedTime -match $email. It is trying to -match the ReceivedTime to an regex. But the regex you provide is the whole $email. Take a look at about_Comparison_Operators