# 如何透過 PowerShell 輸出 Exchange Online / Outlook 之中所有郵件資料夾

我使用 Outlook 應該有將近 20 年的歷史了，郵件資料夾我一直以為只有幾百個，但即便我想整理，也不知道從何著手，因為會花我太多時間，而且很難整理。我剛剛透過 PowerShell 計算了一下我的 Outlook 郵件資料夾到底有多少個，結果是驚人的 `1,101` 個，真的好可怕的多。這篇文章我就來分享幾個好用的 PowerShell 指令檔，幫助我快速整理出資料夾一覽表。

![Mailbox](https://stwillblogassets.blob.core.windows.net/files/images/external/user-images.githubusercontent.com/898b827b529795cfc2af-209443273-e66a6e5d-a7ee-438a-b475-e90917c5d027.png)

-   [連線至 Exchange Online PowerShell](https://learn.microsoft.com/zh-tw/powershell/exchange/connect-to-exchange-online-powershell?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
    
    這裡我使用 Exchange Online PowerShell V3 模組 (EXO V3)，速度比前一版快很多！👍
    
    ```powershell
    $Credential = Get-Credential -Message "M365 Login" -UserName "你的M365帳號"
    
    Connect-ExchangeOnline -UserPrincipalName "你的M365帳號" -ShowProgress $true -Credential $Credential
    ```
    
-   取得「收件夾」下的資料夾清單
    
    我打算先把所有資料先儲存到 `$MailFolders` 變數中，避免每次換不同命令都要不斷重新抓取資料！
    
    ```powershell
    $MailFolders = Get-MailboxFolder -Identity :\收件匣 -Recurse
    ```
    
-   查看收件夾下有多少資料夾
    
    ```powershell
    $MailFolders.Count
    ```
    
-   將「收件夾」資訊輸出成 CSV 檔
    
    ```powershell
    $MailFolders |
    ConvertTo-Csv -Delimiter ',' -NoTypeInformation |
    Out-File -FilePath g:\MailFoldersAll.csv
    ```
    
-   將「收件夾」資訊輸出成 Excel 檔
    
    你必須先安裝好用的 [ImportExcel](https://www.powershellgallery.com/packages/ImportExcel) 模組，才能使用 `Export-Excel` cmdlet 喔！
    
    ```powershell
    $MailFolders |
    Select-Object Identity,FolderSize,HasSubfolders,MailboxOwnerId,IsValid |
    Export-Excel -Path 'G:\MailFoldersAll.xlsx' -AutoSize -AutoFilter -Show
    ```
    

### 相關連結

-   [PowerShell Gallery | ImportExcel](https://www.powershellgallery.com/packages/ImportExcel)
-   [連線至 Exchange Online PowerShell](https://learn.microsoft.com/zh-tw/powershell/exchange/connect-to-exchange-online-powershell?view=exchange-ps&WT.mc_id=DT-MVP-4015686)
