Using Graph to Cleanup Mailbox Folders

Scenario: You (or someone) have many mailbox folders that must be deleted via logic. Yeah, you have been storing mailbox folders over the years….. It’s out of hand, but no shame to you. Hence the reason why I am writing this post. 

Solution: Graph to the rescue! I use the following commandlets to help me out. 

Requirement: You need to be able to connect-mgGraph where you have access to the mailbox.

#Create a variable for your messy messy mailbox
$email = “steve@Messy.com”

#Pull all root folders into a variable (that is if the mess lives in the root of your mailbox)
$Primary_folders = get-mgusermailfolder -UserId $email -All

#Delete all folders where the name of the folder starts with “Search_”
$Primary_folders | where displayname -like “Search_*” | %{ “Removing $($_.DisplayName)”; Remove-mgusermailfolder -MailFolderId $($_.id) -UserId $email }



BUT WAIT, THERE’S MORE…

#What about those child folders that are messy and not sitting on the root of the mailbox. This time I have a ton of folders under my “Search” Folder: 

$folder = $primary_folders | Where displayname -eq “Search”

$Child_Folders = Get-MgUserMailFolderChildFolder -MailFolderId $($folder.id) -UserId $email -All


#Delete all subfolders that match a pattern in my displayname, such as an old year in the naming convention such as “/2018”.
$Child_Folders | Where displayname -like “*/201*” | %{ “removing $($_.DisplayName)”; Remove-mgusermailfolder -MailFolderId $($_.id) -UserId $email }

Leave a comment