﻿# 如何透過 PowerShell 操作 Exchange Online 與 Outlook 的郵件規則設定

我的 Outlook 郵件規則一共有 `155` 個，多到我幾乎不會去人工檢視這些規則是否還合理，也無法一一開啟檢視，因為透過 Outlook 來管理這些郵件規則實在太沒效率了。前幾天發現，我有幾封郵件怎樣都收不到，也沒在垃圾郵件夾，這才想起我可能之前有設定過郵件規則，不知道分類到哪裡去了，這才讓我起心動念，設法用 PowerShell 來找出我想要的規則集。這篇文章我就來分享幾個好用的 PowerShell 指令。

![Post Office](https://stwillblogassets.blob.core.windows.net/files/images/external/user-images.githubusercontent.com/fcdaf6186b16f476d080-209837147-b67ed968-bc8a-4529-ab7e-4f9e8fbfaa38.png)

### 登入 Exchange Online

```powershell
$UserEmail = "user@example.com"
$Credential = Get-Credential -Message "AzureAD Login" -UserName $UserEmail
Connect-ExchangeOnline -UserPrincipalName $UserEmail -ShowProgress $true -Credential $Credential
```

### 常用的郵件規則指令整理

我透過以下幾個命令，搭配 CSV 匯出與 Excel 批次整理現有的郵件規則，一下子就整理好我所有的郵件規則！

1.  取得所有郵件規則清單
    
    ```powershell
    Get-InboxRule
    ```
    
    我在執行這個 Cmdlet 的規則集中，剛好出現了一個有問題的規則，稍後會介紹刪除郵件規則的方法：
    
    ![Get-InboxRule](https://stwillblogassets.blob.core.windows.net/files/images/external/user-images.githubusercontent.com/f105028bb400d78a33cb-209786417-f03f15be-6697-46ff-8a2f-dfa29dfbae68.png)
    
    顯示特定幾個重要欄位
    
    ```powershell
    $MyInboxRules = Get-InboxRule
    $MyInboxRules | select Name,Enabled,Priority,MoveToFolder,From,SentTo| ft
    ```
    
2.  快速搜尋出有問題的郵件規則
    
    如果要快速找出一個規則，可以直接傳入規則名稱，非常簡單：
    
    ```powershell
    Get-InboxRule "518人力銀行"
    ```
    
    如果要透過「關鍵字」快速找出所有相關的郵件規則，可以這樣寫：
    
    ```powershell
    Get-InboxRule | where {$_.Name -like '`[不重要`] *'}
    ```
    
3.  刪除郵件規則
    
    刪除郵件規則最簡單的寫法是這樣：
    
    ```powershell
    Remove-InboxRule "518人力銀行"
    ```
    
    ![Remove-InboxRule 518人力銀行](https://stwillblogassets.blob.core.windows.net/files/images/external/user-images.githubusercontent.com/50dff3021e02fa5e8747-209789657-927d003b-2a77-4e6b-9b32-3e431540f02c.png)
    
    如果要刪除多組郵件規則
    
    ```powershell
    Get-InboxRule | where {$_.Name -like '*104*'} | Remove-InboxRule -Confirm:$false
    ```
    
    ![Get-InboxRule | where {$\_.Name -like '104'} | Remove-InboxRule](https://stwillblogassets.blob.core.windows.net/files/images/external/user-images.githubusercontent.com/810bebd145ccb3534f8d-209791118-0abe8e7f-5815-43ec-baf6-96bb1c52b273.png)
    
4.  停用/啟用郵件規則
    
    ```powershell
    Disable-InboxRule "[電子報] Costco Taiwan"
    ```
    
    ```powershell
    Enable-InboxRule "[電子報] Costco Taiwan"
    ```
    
5.  匯出所有郵件規則
    
    匯出 CSV 格式：
    
    ```powershell
    Get-InboxRule |
    Export-Csv -Path 'G:\MyInboxRules.csv' -NoTypeInformation -Encoding utf8
    ```
    
    匯出 Excel 格式：
    
    ```powershell
    Get-InboxRule |
    Export-Excel -Path 'G:\MyInboxRules.xlsx' -AutoSize -AutoFilter -Show
    ```
    
    > 你必須先安裝好用的 [ImportExcel](https://www.powershellgallery.com/packages/ImportExcel) 模組，才能使用 `Export-Excel` cmdlet 喔！
    
6.  調整郵件規則優先權
    
    以下範例是將該郵件規則的優先權設定為 `10`：
    
    ```powershell
    Set-InboxRule '不太重要的郵件自動分類' -Priority 10
    ```
    
    如果已經有個優先權為 `10` 的郵件規則，原本的郵件規則的優先權編號會自動往前修正 `1` 號，但如果無法往前修正的話 (例如 `1` ~ `9` 都有規則在用了)，這個規則就會新增為 `11` 優先權，而原本的 `11` 就會變 `12`，依此類推！
    
    > 如果想將郵件規則調整為「最高優先權」的話，可以指定編號為 `0`，當你設定為 `0` 的話，最後還是會重新編號為 `1`，所有的優先權編號都是從 `1` 開始計算的，其他規則就會全部向後加 `1`！
    
7.  將郵件規則更名
    
    ```powershell
    Set-InboxRule 'Costco Taiwan' -Name '[電子報] Costco Taiwan'
    ```
    
    改名時順便調整規則優先權
    
    ```powershell
    Set-InboxRule 'Costco Taiwan' -Name '[電子報] Costco Taiwan' -Priority 999
    ```
    
8.  重新排序郵件規則優先權
    
    依照 `From` 寄件者信箱進行排序這些郵件規則
    
    ```powershell
    Get-InboxRule | where {$_.Name -like '`[不重要`] *'} | Sort-Object -Property From | foreach {
      echo "$($_.Name): Set-InboxRule $($_.Identity) -Priority 999"
      Set-InboxRule $($_.Identity) -Priority 999
    }
    ```
    

### 建立郵件規則

由於郵件規則可以設定的相當複雜，所以建立郵件規則的參數超級多，我這裡就整理我常用的幾個規則就好：

1.  將特定「寄件者」送入特定郵件資料夾，優先權設定為 `999`，並且停止處理其他規則
    
    我個人每天會收到數百封郵件，不靠郵件規則我根本就不用做事了。所以我會把一些不太重要的郵件先移到一個名為 `!! 不重要` 的郵件資料夾中，等有空的時候才會去翻來看。不過，我這個習慣用了很多年了，目前累積未看的郵件大概有 `68,953` 封信，我覺得這樣很好！😆
    
    ```powershell
    New-InboxRule `
      -Name '[不重要] 兩廳院代售票券節目電子報快訊' `
      -From 'customerservice@mail.npac-ntch.org' `
      -MoveToFolder ':\收件匣\!! 不重要' `
      -MarkImportance "Low" `
      -Priority 999 `
      -StopProcessingRules:$true
    ```
    
    > 如果不指定 `-Priority` 的話，預設值為 `1` (最高優先權)
    
    這裡的 `-MoveToFolder` 要使用 `MailboxID:\ParentFolder\SubFolder` 這種格式！你可以透過以下命令查出所有可用的資料夾名稱：
    
    ```powershell
    Get-MailboxFolder -Identity :\收件匣 -Recurse | select Identity
    ```
    
2.  將「我」出現在 `To` 欄位的郵件都標示為重要郵件
    
    由於這條規則可能會跟我的 `[不重要]` 郵件相衝突，所以我要把**郵件規則**的**優先權**設定的高一些，並且刻意不加上 `-StopProcessingRules:$true` 參數，好讓後面的郵件規則可以繼續判斷！
    
    ```powershell
    New-InboxRule `
      -Name '[重要] 有我在 To 欄位的郵件' `
      -MyNameInToBox $true `
      -MarkImportance High `
      -Priority 0
    ```
    
    ```powershell
    New-InboxRule `
      -Name '[重要] 只寄給我的郵件' `
      -SentOnlyToMe $true `
      -MarkImportance High `
      -Priority 0
    ```
    
    > 注意: 只要你使用了 `-MarkImportance` 參數設定規則，該規則就會從 Outlook 中消失，這個問題應該是個 Bug，等微軟修復！
    

### 每個郵件規則物件的屬性

以下我列出特定一條 `InboxRule` 的所有屬性清單，方便撰寫腳本時查閱：

```powershell
Get-InboxRule 5044794974520999938 | fl
```

```
Description                           : If the message:
                                                the message was received from 'MMA@mx1.edm.sinopac.com'
                                        Take the following actions:
                                                move the message to folder 'Sino 永豐銀行'
                                                and stop processing more rules on this message

Enabled                               : True
Identity                              : will\5044794974520999938
InError                               : False
ErrorType                             : None
Name                                  : [銀行] MMA@mx1.edm.sinopac.com
Priority                              : 14
RuleIdentity                          : 5044794974520999938
SupportedByTask                       : True
Legacy                                :
BodyContainsWords                     : {}
ExceptIfBodyContainsWords             : {}
FlaggedForAction                      :
ExceptIfFlaggedForAction              :
FromAddressContainsWords              : {}
ExceptIfFromAddressContainsWords      : {}
From                                  : {"MMA@mx1.edm.sinopac.com" [SMTP:MMA@mx1.edm.sinopac.com]}
ExceptIfFrom                          :
HasAttachment                         : False
ExceptIfHasAttachment                 : False
HasClassification                     :
ExceptIfHasClassification             :
HeaderContainsWords                   : {}
ExceptIfHeaderContainsWords           : {}
MessageTypeMatches                    :
ExceptIfMessageTypeMatches            :
MyNameInCcBox                         : False
ExceptIfMyNameInCcBox                 : False
MyNameInToBox                         : False
ExceptIfMyNameInToBox                 : False
MyNameInToOrCcBox                     : False
ExceptIfMyNameInToOrCcBox             : False
MyNameNotInToBox                      : False
ExceptIfMyNameNotInToBox              : False
ReceivedAfterDate                     :
ExceptIfReceivedAfterDate             :
ReceivedBeforeDate                    :
ExceptIfReceivedBeforeDate            :
RecipientAddressContainsWords         : {}
ExceptIfRecipientAddressContainsWords : {}
SentOnlyToMe                          : False
ExceptIfSentOnlyToMe                  : False
SentTo                                :
ExceptIfSentTo                        :
SubjectContainsWords                  : {}
ExceptIfSubjectContainsWords          : {}
SubjectOrBodyContainsWords            : {}
ExceptIfSubjectOrBodyContainsWords    : {}
WithImportance                        :
ExceptIfWithImportance                :
WithinSizeRangeMaximum                :
ExceptIfWithinSizeRangeMaximum        :
WithinSizeRangeMinimum                :
ExceptIfWithinSizeRangeMinimum        :
WithSensitivity                       :
ExceptIfWithSensitivity               :
ApplyCategory                         : {}
ApplySystemCategory                   : {}
CopyToFolder                          :
DeleteMessage                         : False
DeleteSystemCategory                  : {}
ForwardAsAttachmentTo                 :
ForwardTo                             :
MarkAsRead                            : False
MarkImportance                        :
MoveToFolder                          : Sino 永豐銀行
PinMessage                            : False
RedirectTo                            :
SendTextMessageNotificationTo         : {}
SoftDeleteMessage                     : False
StopProcessingRules                   : True
MailboxOwnerId                        : will
IsValid                               : True
ObjectState                           : Unchanged
```

### 相關連結

-   [ExchangePowerShell Module | Microsoft Learn](https://learn.microsoft.com/en-us/powershell/module/exchange/?view=exchange-ps&WT.mc_id=DT-MVP-4015686#mailboxes)
    -   [Get-InboxRule](https://learn.microsoft.com/en-us/powershell/module/exchange/get-inboxrule?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
    -   [Set-InboxRule](https://learn.microsoft.com/en-us/powershell/module/exchange/set-inboxrule?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
    -   [Remove-InboxRule](https://learn.microsoft.com/en-us/powershell/module/exchange/remove-inboxrule?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
    -   [Enable-InboxRule](https://learn.microsoft.com/en-us/powershell/module/exchange/enable-inboxrule?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
    -   [Disable-InboxRule](https://learn.microsoft.com/en-us/powershell/module/exchange/disable-inboxrule?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
    -   [New-InboxRule](https://learn.microsoft.com/en-us/powershell/module/exchange/new-inboxrule?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
-   [Find the permissions required to run any Exchange cmdlet](https://learn.microsoft.com/en-us/powershell/exchange/find-exchange-cmdlet-permissions?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
