I am trying to write a powershell script to download a csv emailed daily save it to a folder, and then process it using powershell/excel. I have already written the powershell to open up the file and process it using a excel macro written in VBA, but I cannot seem to get this code below to download the attachment. The file name that is emailed is typically exceptions_123456.csv but filenames sometimes change, but its always .CSV and is the only csv file I get daily. so I want to download any csv file emailed to me on todays date sent to my inbox.
this is the code I have tried, it doesnt seem to work. I do not get any errors, I even tried replacing the $today variable with today's date manually "03/23/2023" and it wont download either. not sure where the issue is.
Add-type -assembly "Microsoft.Office.Interop.Outlook"
$olDefaultFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = New-Object -comobject Outlook.Application
$mapi = $outlook.GetNameSpace(“MAPI”)
$inbox = $mapi.GetDefaultFolder(6)
$FilePath= "c:\exceptions\"
$today = Get-Date -Format "MM/dd/yyyy"
$subfolder.Items | Where-Object {$_.receivedtime -match $today -and $($_.attachments).filename -match '.csv'} | foreach {
foreach($attachment in $($_.attachments | where filename -match '.csv'))
{
Write-Host Downloading $attachment.filename to $filepath -ForegroundColor green
$attachment.SaveAsFile((join-path $FilePath $attachment.filename))
}
}