List All Folders in a Mailbox using EWS API and PowerShell

We can use the EWS Managed API to work with items in a mailbox in Exchange and Exchange Online. You can create, get, update, and delete messages and calendar appointments by using the EWS API. In this post, we will explore how to use the EWS API to get all the folders from a user’s mailbox using PowerShell.

The below script uses the EWS API 2.2 DLL. Install the EWS Managed API 2.2 and ensure the DLL file (Microsoft.Exchange.WebServices.dll) is available in the correct location. You can download the EWS API 2.2 setup from this GitHub link

The below script retrieves the folders under the Inbox folder from the given user mailbox. You can change the WellKnownFolderName (ex: SentItems, DeletedItems) to list subfolders from different root folders. The final command lists the folders with the properties – display name, total messages count and unread messages count.

#Import EWS API dll
Import-Module "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"

#Proivde the mailbox user credentials
$PSCredential = Get-Credential

$Service = [Microsoft.Exchange.WebServices.Data.ExchangeService]::new()
$Service.Credentials = New-Object System.Net.NetworkCredential($PSCredential.UserName.ToString(),$PSCredential.GetNetworkCredential().password.ToString())
$Service.Url = "https://outlook.office365.com/EWS/Exchange.asmx"

$Folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(100)
$Folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
$Folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
$Folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
$FoldersResult = $Service.FindFolders([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $Folderview)

#List folders result
$FoldersResult | Select DisplayName,TotalCount,UnreadCount,FolderClass
Advertisement

4 thoughts on “List All Folders in a Mailbox using EWS API and PowerShell”

  1. Hi,
    any idea where the problem is, if I get returned a “the request failed. RPC Server has returned an error: 401 not authorized” ? (translated from German)

    + $FoldersResult = $Service.FindFolders([Microsoft.Exchange.Webservices …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException

    The entered credentials are domain administrator, which is also the exchange Administrator

    Reply

Leave a Comment