如何使用 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)。不要忘記關注我們並分享這篇文章。