GraphAPI – Find Messages in a Mailbox in specific folders via PowerShell

Scenario: You want to pull a list of messages using GraphAPI via PowerShell for a specific Mailbox.

Prerequisites: You already have the following configured:
Registered App in Azure: An Azure Registered app to connect to with Application Permissions for Mail.Read, Mail.ReadWrite, Mail.ReadBasic.All, and Mail.Send. (Not all permissions listed may be necessary for the specific function below)
Bearer Authentication Token: A method for pulling back a bearer token and storing it to pass Authorization into your RestAPI package (See my previous post about get-accesstoken). The get-accesstoken authenticates against your Registered App in Azure.

Scriptlets in PowerShell:

#1. Define $mbx
$mbx = ""

#2. Build your $AppURI (Examples)
$appuri = "$mbx/mailfolders/inbox/Messages"   #using common folder names
$appuri = "$mbx/mailfolders/AAMkADY3ODhkMDNlLTRjM2YtNDJjYi04YTkzLTFmNjFhYTcyMjA2NwAuAAAAAAAM5kRh6DylRZ4XsImGGVClAQA8oulgK3qgQ659gFhlXH_UAAAAAAEMAAA=/Messages"  #Using Base64 naming for any folder in mailbox
$appuri = "$mbx/mailfolders('RecoverableItemsDiscoveryHolds')/Messages"
$appuri = "$mbx/mailfolders('RecoverableItemsPurges')/Messages"

#3. Run the following in a Do-While loop so it collects for than 10 messages at a time:
          #Create your Collection Variable
                $messages = @()
            #Run a Do-While Loop
                    "Running $appUri"
                    $RestSplat = @{
                        URI = $appuri
                        Headers = $(get-accesstoken)
                        Method = 'GET'
                        ContentType = "application/json"
                    $Tempresults = Invoke-RestMethod @RestSplat
                    $messages += $tempresults.value
                    $appuri = $tempresults."@odata.NextLink"
                    }While($appuri -ne $null)

          #Display your Messages

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: