使用 Microsoft Graph PowerShell 导出 Microsoft 365 邮箱
带有 Microsoft Graph PowerShell 的 Get-MgUserMessageContent cmdlet 提供了一种以 .eml 格式将电子邮件导出到本地计算机的方法,任何人都可以阅读该格式。在这篇文章中,我将向您展示如何从组织中的任何 Exchange Online (M365) 邮箱批量导出电子邮件。此外,如何过滤导出特定日期范围内且主题行中包含特定信息的电子邮件。
要求
此脚本使用以下 Microsoft Graph PowerShell 模块:
- Microsoft.Graph.Authentication
- Microsoft.Graph.Mail
您还需要租户中的全局管理员帐户才能同意以下权限:
- 邮件.阅读
有关这些要求的支持,请参阅我的帖子:如何安装 Microsoft Graph PowerShell 模块。
Mail.Read 权限仅在应用程序上下文中可用。为此,您需要在 Microsoft Entra 中注册一个新应用程序,并通过 PowerShell 在应用程序上下文中连接到它。请参阅我的文章使用客户端密钥连接到 Microsoft Graph PowerShell。
备份Exchange在线邮箱
仅应在某些情况下使用 Microsoft Graph PowerShell 备份 Exchange Online 电子邮件。例如,用户已离开您的组织,您需要 .eml 格式的用户文件副本。或者您需要下载特定日期之间用户电子邮件的副本。
您可以使用以下脚本下载用户邮箱中所有电子邮件的副本(包括电子邮件附件)。
## Define information here
$ApplicationId = ""
$SecuredPassword = ""
$tenantID = ""
$UserID "" #Example: [email
$filepath = "" #Example: C:\temp\
#Connect to Microsoft Graph
$SecuredPasswordPassword = ConvertTo-SecureString `
-String $SecuredPassword -AsPlainText -Force
$ClientSecretCredential = New-Object `
-TypeName System.Management.Automation.PSCredential `
-ArgumentList $ApplicationId, $SecuredPasswordPassword
Connect-MgGraph -TenantId $tenantID -ClientSecretCredential $ClientSecretCredential
#Store all emails
##Add filter if required
$messages = Get-MgUserMessage -UserId $userid -all
#Download all emails
Foreach ($message in $messages) {
$file = ($File = "$($message.subject) $($message.ReceivedDateTime).eml").Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
$outfile = $filepath + $file
try {
Get-MgUserMessageContent -UserId $userid -MessageId $message.id -OutFile $outfile
}
Catch {
LogWrite "Unable to export " $message.Subject
}
}定义备份 Exchange Online 电子邮件的日期范围
如果您只想导出特定日期范围内的电子邮件,可以使用过滤器查询来限制结果。
下面,我使用 AND 运算符组合了两个过滤器,以仅导出 1 月 1 日到 1 月 9 日之间的电子邮件。
Get-MgUserMessage -UserId $userid -all `
-filter "ReceivedDateTime ge 2024-01-01 AND ReceivedDateTime le 2024-01-09"该过滤器可以进一步扩展,以包括主题行中具有特定文本字符串的消息。例如:
我使用了反引号`,使其无需滚动即可阅读。跨度>
Get-MgUserMessage -UserId $userid -all `
-filter "ReceivedDateTime ge 2024-01-01 AND ReceivedDateTime le 2024-01-09 `
AND contains(Subject, 'New Device')" `
| Select Subject, ReceivedDateTime包起来
批量下载电子邮件文件不应被视为为已离开公司的用户存储邮件的唯一“备份”解决方案。您仍应考虑使用第三方备份解决方案和/或将邮箱维护为共享邮箱。但是,它提供了一种方便的解决方案,可以在备份、调查或合规原因的情况下导出批量电子邮件。

