Reputation: 25
I have the following code to save email attachments using powershell in outlook.
$o = New-Object -comobject outlook.application
$n = $o.GetNamespace("MAPI")
$Account = $n.Folders | ? { $_.Name -eq ''Mailbox};
$f = $Account.Folders | ? { $_.Name -match 'Inbox' };
$filepath = "c:\temp\"
$f.Items| Where-Object {$_.SenderName -eq "Sender"} | foreach {
$Subject = $_.Subject
$_.attachments|foreach {
Write-Host $_.filename
$a = $_.filename
If ($a.Contains("xls")) {
$_.saveasfile((Join-Path $filepath "$Subject.xls"))
}
}
}
The problem with this is that is goes through my entire inbox and takes a while. Is there a way for it to only look at the last week or so of data? Or maybe yesterdays received emails only? I would like it to look at the most recent emails first and when it finds the first match to stop looking... The email it is trying to save is sent to me daily and can stop after finding the first instance.
Thanks!
Upvotes: 1
Views: 1906
Reputation: 694
I do something similar with cleaning up files on a server that are older than a certain date. Perhaps it will help find a solution here?
I create a variable for my date range
#creates a date that is 14 days before today.
$limit = (Get-Date).AddDays(-15)
In my code I then add in the following condition
Where-Object( $_.PSIsContainer -and ($_.CreationTime -lt $limit))
Pipe in this clause where you filter your emails and I suspect that will add the limit you desire. Hopefully this helps.
Upvotes: 1
Reputation: 66255
Use Items.Find/FindNext
or Items.Restrict
to create a restriction on the ReceivedTime
property: "[ReceivedTime] >= '10/09/2016' "
Upvotes: 0