如何使用 PowerShell 搜索电子邮件

Jacki

在 Exchange Online 邮箱中搜索邮件的一个绝佳方法是使用 PowerShell。您可以根据自己的喜好调整命令并获得所需的结果。此外,将结果导出到 CSV 文件也很棒,因此您可以在其中进行过滤。在本文中,您将学习如何使用 PowerShell 搜索电子邮件。

安装 Microsoft Graph PowerShell

以管理员身份运行 Windows PowerShell 并安装 Microsoft Graph PowerShell。

Install-Module Microsoft.Graph -Force

重要的:在运行 cmdlet 或脚本之前,请务必更新到最新的 Microsoft Graph PowerShell 模块版本,以防止出现错误和不正确的结果。

在 Microsoft Entra 中配置应用程序注册

在运行命令或脚本之前,必须首先创建具有正确权限和客户端密钥的应用注册,以通过 Microsoft Graph PowerShell 进行身份验证。

1. 注册新应用

在 Microsoft Entra ID 中注册新应用程序:

  1. 登录到微软 Entra 管理中心
  2. 点击身份 > 应用程序 > 应用程序注册
  3. 点击新注册
  1. 为应用程序命名搜索邮件
  2. 选择仅此组织目录中的帐户(仅限 EXOIP – 单租户)
  3. 点击登记

应用程序Search-Mail 已成功创建。复制下面的值并将其粘贴到记事本中,因为稍后连接到 Microsoft Graph PowerShell 时将需要它们。

  1. 复制应用程序(客户端)ID
  2. 复制目录(租户)ID

2.分配API权限

为您在上一步中注册的应用程序分配 API 权限:

  1. 点击API权限
  2. 点击添加权限
  1. 点击微软API
  2. 点击微软图谱
  1. 点击应用程序权限
  2. 搜索用户.阅读.全部
  3. 选择用户 > 用户.阅读.全部
  1. 搜索邮件阅读
  2. 选择邮件 > 邮件.阅读
  3. 点击添加权限

API权限添加成功。下一步是授予管理员同意。

您必须向管理员授予您在上一步中选择的权限的同意:

  1. 点击授予 EXOIP 管理员同意
  2. 点击是的
  1. 绿色复选标记表明您已成功授予管理员同意

4. 创建客户端密码

在 Microsoft Entra 中注册新应用程序、分配 API 权限并授予管理员同意后,您需要创建客户端密钥。

要在 Microsoft Entra ID 中为您的应用程序创建客户端密钥,请按照下列步骤操作:

  1. 点击证书和秘密
  2. 点击客户端机密 > 新客户端机密
  3. 类型描述
  4. 选择一个截止日期
  5. 点击添加

笔记:客户秘密的有效期最长为 24 个月(2 年)。您始终可以使用 PowerShell 更新 Microsoft Entra ID 中的客户端密钥。

  1. 复制 Client Secret 值并将其保存到记事本中

使用客户端密钥连接到 Microsoft Graph PowerShell

您需要更改以下参数的值才能使用客户端密钥连接到 MS Graph PowerShell:

  • 键入应用程序客户端 ID值在2号线
  • 键入目录租户 ID值在3号线
  • 键入客户端秘密值值在4号线

运行下面的 PowerShell 脚本。

# Configuration
$ClientId = "c6787ff5-08ec-4e96-b4d2-1d1782303310"
$TenantId = "eb403171-a4ec-4d98-a08f-1876318c9deb"
$ClientSecret = "6_q8Q~X9e-fjwWhVVP_WWx~ua4JMI.BWkI7Q7b7B"

# Convert the client secret to a secure string
$ClientSecretPass = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force

# Create a credential object using the client ID and secure string
$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ClientId, $ClientSecretPass

# Connect to Microsoft Graph with Client Secret
Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $ClientSecretCredential

搜索特定用户的电子邮件

获取来自特定用户的所有消息。

$User = "[email protected]"

Get-MgUserMessage -All -UserId "$User" |
Select-Object Subject, InternetMessageId, ReceivedDateTime,
@{Name = "Sender"; Expression = { $_.Sender.EmailAddress.Address } }, 
@{Name = "Recipients"; Expression = { $_.ToRecipients.EmailAddress.Address -join ', ' } } |
Out-GridView

获取特定用户已阅读的所有消息。

$User = "[email protected]"

Get-MgUserMessage -All -UserId "$User" -Filter "IsRead eq true" |
Select-Object Subject, InternetMessageId, ReceivedDateTime,
@{Name = "Sender"; Expression = { $_.Sender.EmailAddress.Address } }, 
@{Name = "Recipients"; Expression = { $_.ToRecipients.EmailAddress.Address -join ', ' } } |
Out-GridView

获取来自特定用户的所有未读消息。

$User = "[email protected]"

Get-MgUserMessage -All -UserId "$User" -Filter "IsRead eq false" |
Select-Object Subject, InternetMessageId, ReceivedDateTime,
@{Name = "Sender"; Expression = { $_.Sender.EmailAddress.Address } }, 
@{Name = "Recipients"; Expression = { $_.ToRecipients.EmailAddress.Address -join ', ' } } |
Out-GridView

按日期搜索电子邮件

搜索特定日期之后来自特定用户的电子邮件。

$User = "[email protected]"
$Date = "2024-01-01"

Get-MgUserMessage -All -UserId "$User" -Filter "ReceivedDateTime gt $Date" |
Select-Object Subject, InternetMessageId, ReceivedDateTime,
@{Name = "Sender"; Expression = { $_.Sender.EmailAddress.Address } }, 
@{Name = "Recipients"; Expression = { $_.ToRecipients.EmailAddress.Address -join ', ' } } |
Out-GridView

搜索有关主题的电子邮件

搜索以特定主题开头的电子邮件。

推荐阅读:以下是如何在 Outlook 中搜索电子邮件 |简单的步骤

$Subject = "The subject"
$user = "[email protected]"

Get-MgUserMessage -All -UserId "$User" -Filter "startswith(Subject,'$Subject')" |
Select-Object Subject, InternetMessageId, ReceivedDateTime,
@{Name = "Sender"; Expression = { $_.Sender.EmailAddress.Address } }, 
@{Name = "Recipients"; Expression = { $_.ToRecipients.EmailAddress.Address -join ', ' } } |
Out-GridView

搜索与主题相同的电子邮件。

$Subject = "The specific subject"
$user = "[email protected]"

Get-MgUserMessage -All -UserId "$user" -Filter "Subject eq '$Subject'" | 
Select-Object Subject, InternetMessageId, ReceivedDateTime, 
@{Name = "Sender"; Expression = { $_.Sender.EmailAddress.Address } }, 
@{Name = "Recipients"; Expression = { $_.ToRecipients.EmailAddress.Address -join ', ' } } | 
Out-GridView

搜索过去 30 天的电子邮件

让我们搜索过去 30 天内组织中收件人和发件人的所有电子邮件。结果将出现在网格视图并导出为 CSV 文件。

搜索过去 30 天内组织中的所有电子邮件。

# Get all users
$users = Get-MgUser -All

# Initialize a List to store the data
$Report = [System.Collections.Generic.List[Object]]::new()

# Determine the date 30 days prior to today
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-dd")

# Loop through each user
foreach ($user in $users) {
    # Ensure the user has an associated email address
    if ($user.Mail) {
        $messages = Get-MgUserMessage -UserId $user.Id -All -Filter "ReceivedDateTime ge $startDate" -ErrorAction SilentlyContinue
        foreach ($message in $messages) {
            $ReportLine = [PSCustomObject]@{
                ReceivedDateTime  = $message.ReceivedDateTime
                Subject           = $message.Subject
                Sender            = $message.Sender.EmailAddress.Address -join ','
                Recipient         = $message.ToRecipients.EmailAddress.Address -join ','
                InternetMessageId = $message.InternetMessageId
            }
            $Report.Add($ReportLine)
        }
    }
}

# Display and export the data
$Report | Out-GridView
$Report | Export-Csv -Path "C:tempAll_emails.csv" -NoTypeInformation -Encoding utf8

搜索组织中过去 30 天内发送给特定收件人的所有电子邮件。

# Email address of the recipient you want to filter
$recipientEmailAddress = "[email protected]"

# Get all users
$users = Get-MgUser -All

# Initialize a List to store the data
$Report = [System.Collections.Generic.List[Object]]::new()

# Determine the date 30 days prior to today
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-dd")

# Loop through each user
foreach ($user in $users) {
    # Ensure the user has an associated email address
    if ($user.Mail) {
        $messages = Get-MgUserMessage -UserId $user.Id -All -Filter "ReceivedDateTime ge $startDate" -ErrorAction SilentlyContinue
        foreach ($message in $messages) {
            # Check if the recipient matches the desired email address
            if ($message.ToRecipients.EmailAddress.Address -eq $recipientEmailAddress) {
                $ReportLine = [PSCustomObject]@{
                    ReceivedDateTime  = $message.ReceivedDateTime
                    Subject           = $message.Subject
                    Sender            = $message.Sender.EmailAddress.Address
                    Recipient         = $message.ToRecipients.EmailAddress.Address
                    InternetMessageId = $message.InternetMessageId
                }
                $Report.Add($ReportLine)
            }
        }
    }
}

# Display and export the data
$Report | Out-GridView
$Report | Export-Csv -Path "C:tempRecipient_emails.csv" -NoTypeInformation -Encoding utf8

搜索组织中过去 30 天内由特定发件人发送的所有电子邮件。

# Email address of the sender you want to filter
$senderEmailAddress = "[email protected]"

# Get all users
$users = Get-MgUser -All

# Initialize a List to store the data
$Report = [System.Collections.Generic.List[Object]]::new()

# Determine the date 30 days prior to today
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-dd")

# Loop through each user
foreach ($user in $users) {
    # Ensure the user has an associated email address
    if ($user.Mail) {
        $messages = Get-MgUserMessage -UserId $user.Id -All -Filter "ReceivedDateTime ge $startDate" -ErrorAction SilentlyContinue
        foreach ($message in $messages) {
            if ($message.Sender.EmailAddress.Address -eq $senderEmailAddress) {
                $ReportLine = [PSCustomObject]@{
                    ReceivedDateTime  = $message.ReceivedDateTime
                    Subject           = $message.Subject
                    Sender            = $message.Sender.EmailAddress.Address
                    Recipient         = ($message.ToRecipients.EmailAddress.Address -join ',')
                    InternetMessageId = $message.InternetMessageId
                }
                $Report.Add($ReportLine)
            }
        }
    }
}

# Display and export the data
$Report | Out-GridView
$Report | Export-Csv -Path "C:tempSender_emails.csv" -NoTypeInformation -Encoding utf8

就是这样!

结论

您学习了如何使用 PowerShell 搜索电子邮件。首先,在 Microsoft Entra 中设置具有正确权限的应用程序。之后,使用 Microsoft Graph PowerShell 连接到应用程序。最后,运行命令以使用 PowerShell 搜索电子邮件。

您喜欢这篇文章吗?您可能还喜欢如何在 Microsoft 365 中阻止顶级域 (TLD)。不要忘记关注我们并分享这篇文章。