Reputation: 354
I'm working on something that is extracting information from my desktop Outlook application. It works for most of the folders I've tried it on, but for some that have nearly a decade of e-mails, I get a "Exception getting 'ReceivedTime': 'Insufficient memory to continue the execution of the program." This is what I'm trying:
# New Outlook object
$ol = new-object -comobject "Outlook.Application";
# MAPI namespace
$mapi = $ol.getnamespace("mapi");
# Folder/Inbox
$folder = $mapi.Folders.Item('[email protected]').Folders.Item('Inbox')
# Sort by the Received Time
$contents = $folder.Items | sort ReceivedTime
# Get the first element in the array, convert to JSON, and then output to file
echo $contents[0] | convertTo-Json | Out-File C:\Users\ME\outlook_1.json -Encoding UTF8
Is there a better way of approaching this? I'm on Powershell 5.1.
EDIT: I've also tried this, which is looping through the array and then breaking on the first instance, but received the same error:
# New Outlook object
$ol = new-object -comobject "Outlook.Application";
# MAPI namespace
$mapi = $ol.getnamespace("mapi");
# Folder/Inbox
$folder = $mapi.Folders.Item('[email protected]').Folders.Item('Inbox')
# Sort by the Received Time
$contents = $folder.Items | sort ReceivedTime
$i = 1
foreach($item in $contents){
if (-not ([string]::IsNullOrEmpty($item))){
echo $item | convertTo-Json | Out-File Out-File C:\Users\ME\outlook_1.json -Encoding UTF8-Encoding UTF8
Break
}
}
Upvotes: 0
Views: 1420
Reputation: 66215
Sort the items collection using Items.Sort("ReceivedTime", false)
, then read the first item using Items(1)
.
Make sure you store Items
collection in a variable instead of accessing MAPIFolder.Items
multiple times, otherwise you will get a brand new Items
object every time you do that.
EDIT: I'm the OP of the question and am putting the correct code here for those who might be as dense as I am and not initially realize what is being said!
# New Outlook object
$ol = new-object -comobject "Outlook.Application";
# MAPI namespace
$mapi = $ol.getnamespace("mapi");
$folder = $mapi.Folders.Item('[email protected]').Folders.Item('Inbox')
# Get the items in the folder
$contents = $folder.Items
# Sort the items in the folder by the metadata, in this case ReceivedTime
$contents.Sort("ReceivedTime")
# Get the first item in the sorting; in this case, you will get the oldest item in your inbox.
$item = $contents.GetFirst()
echo $item
# If instead, you wanted to get the newest item, you could do the same thing but do $item = $contents.GetLast()
Upvotes: 2