Reputation: 3141
I want to search a specific Outlook folder, find the most recently-sent email, and save its attachments to a specific dir.
I wrote the following script, but it does not work. Can someone please suggest what needs to be changed in order for it to work?
Also - where can I find a list of Outlook- and Office-specific methods and properties I can use in PowerShell? I tried googling but could not find an official MSDN page for it.
#file path
$filepath = “C:\folder”
$account = "[email protected]"
#set outlook to open
$o = New-Object -comobject outlook.application
$n = $o.GetNamespace(“MAPI”)
$Account = $n.Folders | ? { $_.Name -eq $account };
$f = $Account.Folders | ? { $_.Name -match 'FolderNameToSearch' };
$date = $f.Items| Select-Object -Property ReceivedTime | Sort-Object ReceivedTime -Descending | Select-Object -Index 0
#Write-Host $date
$f.Items | foreach
{
if ($_.ReceivedTime -match $date )
{
$_.attachments | foreach
{
#Write-Host $_.filename
$a = $_.filename
$_.saveasfile((Join-Path $filepath $a))
}
}
}
Edit 3/4/14 - I stepped through the script, and I believe it is failing on $_.ReceivedTime -match $date
I added the following code to test the values of the Email ReceivedTime
datestamps vs the datestamp stored by $date
:
Write-Host "The date I am looking for is $date"
$f.Items | foreach {
Write-Host $_.ReceivedTime
}
and here is part of the output:
The date I am looking for is @{ReceivedTime=03/04/2014 03:16:08}
3/4/2014 3:16:08 AM
Even though the dates are the same, the data types are different. What is the most elegant way to get $date
to datetime or vice versa?
Upvotes: 3
Views: 3516
Reputation: 36297
First, you're trying too hard. You're looping through your emails twice looking for the exact same email, and that's just redundant. Second, Get-Date <DateTime Object/DateTime String>
is your friend, but you don't even need it. If you really, really, really want to sort the emails and select the date/time of the first one, then filter them for that one date/time I suppose you can, and here's what you'd want:
if ((get-date $_.ReceivedTime) -eq (get-date $date))
I think a better solution would be replacing:
$date = $f.Items| Select-Object -Property ReceivedTime | Sort-Object ReceivedTime -Descending | Select-Object -Index 0
with:
$email = $f.Items| Sort-Object ReceivedTime -Descending | Select-Object -First 1
Then you can do things like:
Write-Output "Last email received at $($email.receivedtime), attached file(s) are: (if any)
$email.attachments|%{Write-Output $_.filename}
and
$email.attachments|%{$_.saveasfile((join-path $folder $_.filename))
Personally I'd add a If($email.attachments.count -gt 0){Do Stuff}else{Write-Output "Latest email at $($email.receivedtime) has no attachments!"}
bit in there.
Upvotes: 1