通过 Powershell 获取 Outlook 中最旧的项目

Getting the Oldest Item in Outlook via Powershell

我正在研究从我的桌面 Outlook 应用程序中提取信息的东西。它适用于我试过的大多数文件夹,但对于一些有近十年电子邮件的文件夹,我得到 "Exception getting 'ReceivedTime': 'Insufficient memory to continue the execution of the program." 这就是我正在尝试的:

# New Outlook object
$ol = new-object -comobject "Outlook.Application";

# MAPI namespace
$mapi = $ol.getnamespace("mapi");

# Folder/Inbox
$folder =  $mapi.Folders.Item('name@email.com').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

有没有更好的方法来解决这个问题?我在使用 Powershell 5.1。

编辑:我也试过这个,它循环遍历数组然后在第一个实例上中断,但收到相同的错误:

# New Outlook object
$ol = new-object -comobject "Outlook.Application";

# MAPI namespace
$mapi = $ol.getnamespace("mapi");

# Folder/Inbox
$folder =  $mapi.Folders.Item('name@email.com').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
    }
}

使用 Items.Sort("ReceivedTime", false) 对项目集合进行排序,然后使用 Items(1) 读取第一个项目。

确保将 Items 集合存储在变量中,而不是多次访问 MAPIFolder.Items,否则每次这样做都会得到一个全新的 Items 对象。

编辑:我是问题的 OP,我在这里为那些可能像我一样密集但最初没有意识到所说内容的人提供了正确的代码!

# New Outlook object
$ol = new-object -comobject "Outlook.Application";

# MAPI namespace
$mapi = $ol.getnamespace("mapi");

$folder =  $mapi.Folders.Item('name@gmail.com').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()