当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何使用 PowerShell 搜索电子邮件

作者:精品下载站 日期:2024-12-14 03:37:56 浏览:14 分类:玩电脑

如何使用 PowerShell 搜索电子邮件


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

安装 Microsoft Graph PowerShell

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

Install-Module Microsoft.Graph -Force
Install-Module Microsoft.Graph.Beta -AllowClobber -Force

重要提示:始终安装 Microsoft Graph PowerShellMicrosoft Graph Beta PowerShell 模块。这是因为某些 cmdlet 在最终版本中尚不可用,并且无法运行。在运行 cmdlet 或脚本之前将两个模块更新到最新版本,以防止出现错误和不正确的结果。

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

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

1. 注册新应用

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

  1. 登录 Microsoft Entra 管理中心
  2. 单击身份>应用程序>应用程序注册
  3. 点击新注册

[玩转系统] 如何使用 PowerShell 搜索电子邮件

  1. 将应用程序命名为Search-Mail
  2. 选择仅此组织目录中的帐户(仅限 EXOIP - 单一租户)
  3. 点击注册

[玩转系统] 如何使用 PowerShell 搜索电子邮件

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

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

[玩转系统] 如何使用 PowerShell 搜索电子邮件

2.分配API权限

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

  1. 点击API权限
  2. 点击添加权限

[玩转系统] 如何使用 PowerShell 搜索电子邮件

  1. 点击Microsoft API
  2. 单击Microsoft Graph

[玩转系统] 如何使用 PowerShell 搜索电子邮件

  1. 点击应用程序权限
  2. 搜索User.Read.All
  3. 选择用户 > User.Read.All

[玩转系统] 如何使用 PowerShell 搜索电子邮件

  1. 搜索Mail.Read
  2. 选择邮件 > 邮件.阅读
  3. 点击添加权限

[玩转系统] 如何使用 PowerShell 搜索电子邮件

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

3. 授予管理员同意

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

  1. 点击授予 EXOIP 管理员同意
  2. 单击

[玩转系统] 如何使用 PowerShell 搜索电子邮件

  1. 绿色复选标记表明您已成功授予管理员同意

[玩转系统] 如何使用 PowerShell 搜索电子邮件

4. 创建客户端密钥

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

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

  1. 点击证书和机密
  2. 单击客户端密钥 > 新客户端密钥
  3. 输入描述
  4. 选择到期日期
  5. 点击添加

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

[玩转系统] 如何使用 PowerShell 搜索电子邮件

  1. 复制客户端密钥值并将其保存在记事本中

[玩转系统] 如何使用 PowerShell 搜索电子邮件

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

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

  • 第 2 行中键入应用程序客户端 ID
  • 第 3 行中键入目录租户 ID
  • 第 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

搜索有关主题的电子邮件

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

$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 天内组织中收件人和发件人的所有电子邮件。结果将显示在 Out-GridView 中并导出到 CSV 文件。

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

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

# Create an empty array to store the data
$Data = @()

# 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) {
            $Data += [PSCustomObject]@{
                ReceivedDateTime  = $message.ReceivedDateTime
                Subject           = $message.Subject
                Sender            = $message.Sender.EmailAddress.Address -join ','
                Recipient         = $message.ToRecipients.EmailAddress.Address -join ','
                InternetMessageId = $message.InternetMessageId
            }
        }
    }
}

# Display and export the data
$Data | Out-GridView
$Data | Export-Csv -Path "C:\temp\All_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

# Create an empty array to store the data
$Data = @()

# 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) {
                $Data += [PSCustomObject]@{
                    ReceivedDateTime  = $message.ReceivedDateTime
                    Subject           = $message.Subject
                    Sender            = $message.Sender.EmailAddress.Address
                    Recipient         = $message.ToRecipients.EmailAddress.Address
                    InternetMessageId = $message.InternetMessageId
                }
            }
        }
    }
}

# Display and export the data
$Data | Out-GridView
$Data | Export-Csv -Path "C:\temp\Recipient_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

# Create an empty array to store the data
$Data = @()

# 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) {
                $Data += [PSCustomObject]@{
                    ReceivedDateTime  = $message.ReceivedDateTime
                    Subject           = $message.Subject
                    Sender            = $message.Sender.EmailAddress.Address
                    Recipient         = ($message.ToRecipients.EmailAddress.Address -join ',')
                    InternetMessageId = $message.InternetMessageId
                }
            }
        }
    }
}

# Display and export the data
$Data | Out-GridView
$Data | Export-Csv -Path "C:\temp\Sender_emails.csv" -NoTypeInformation -Encoding utf8

就是这样!

了解更多:导出 Entra ID 应用程序注册证书和机密到期报告 »

结论

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

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

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯