如何使用PowerShell搜索电子邮件

在交换在线邮箱中搜索消息的一种绝佳方法是使用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. 点击登记

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

有关的:

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

2。分配API权限

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

  1. 点击API许可
  2. 点击添加权限
  1. 点击Microsoft API
  2. 点击Microsoft Graph
  1. 点击申请许可
  2. 搜索User.Read.All
  3. 选择用户> user.read.all
  1. 搜索mail.read
  2. 选择邮件>邮件
  3. 点击添加权限

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

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

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

4。创建客户秘密

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

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

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

笔记:客户秘密到期日期最多24个月(2年)。您始终可以使用PowerShell续订Microsoft Entra ID中的客户秘密。

  1. 复制客户端秘密值并将其保存到记事本

用客户秘密连接到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 = ""

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 = ""

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 = ""

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 = ""
$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 = ""

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 = ""

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天的电子邮件

让我们在收件人和发件人上搜索组织中的所有电子邮件。结果将出现在离格视图并将导出到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 = ""

# 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 = ""

# 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)。不要忘记关注我们并分享本文。