Using Remove-MgUserMailFolder in Graph PowerShell

The Remove-MgUserMailFolder cmdlet in the Microsoft Graph PowerShell module allows administrators to delete specific mail folders in a user's mailbox. This article provides a detailed overview of the cmdlet, including its syntax, usage examples, tips, use cases, possible errors, solutions, and a conclusion.


Cmdlet Syntax

Remove-MgUserMailFolder -UserId <String> -MailFolderId <String> [-Confirm] [<CommonParameters>]
  • UserId: The ID of the user whose mail folder needs to be removed. This can be the user's UPN or ID.
  • MailFolderId: The ID of the mail folder to be removed.
  • Confirm: Prompts for confirmation before executing the command.

Usage Examples

Example 1: Remove a Mail Folder by ID by passing UPN

Remove-MgUserMailFolder -UserId "user@domain.com" -MailFolderId "AAMkADI5AAAAAH0"

Example 2: Remove a Mail Folder with Confirmation Prompt

Remove-MgUserMailFolder -UserId "user@domain.com" -MailFolderId "AAMkADI5AAAAAH0" -Confirm:$true

Example 3: Remove a Mail Folder by ID by passing User ID

Remove-MgUserMailFolder -UserId "a1b2c3d4-e5f6-7890-ab12-cd34ef567890" -MailFolderId "AAMkADI5AAAAAH0"

Example 4: Remove All Empty Mail Folders for a User

This helps clean up unused folders in a mailbox.


# Get all mail folders
$Folders = Get-MgUserMailFolder -UserId "john.doe@contoso.com" -All

foreach ($Folder in $Folders) {

# Check if folder has no messages
if ($Folder.TotalItemCount -eq 0) {

Write-Host "Deleting empty folder:" $Folder.DisplayName

Remove-MgUserMailFolder `
-UserId "john.doe@contoso.com" `
-MailFolderId $Folder.Id
}
}

                            

Example 5: Remove All Subfolders Under a Specific Parent Folder

This example deletes all subfolders under a given parent folder (e.g., a custom folder like “Projects”).


$UserId = "john.doe@contoso.com"
$ParentFolderName = "Projects"

# Get the parent folder
$ParentFolder = Get-MgUserMailFolder `
    -UserId $UserId `
    -Filter "displayName eq '$ParentFolderName'"

if ($ParentFolder) {

    # Get all child folders under the parent
    $ChildFolders = Get-MgUserMailFolderChildFolder `
        -UserId $UserId `
        -MailFolderId $ParentFolder.Id `
        -All

    foreach ($Folder in $ChildFolders) {

        Write-Host "Deleting subfolder:" $Folder.DisplayName

        Remove-MgUserMailFolder `
            -UserId $UserId `
            -MailFolderId $Folder.Id
    }
}
else {
    Write-Host "Parent folder not found."
}

                            

Cmdlet Tips

  • Ensure you have the necessary permissions to remove mail folders from the user's mailbox.
  • Use the -Confirm parameter to add a safety prompt before the mail folder is deleted.
  • Double-check the MailFolderId to avoid accidentally deleting the wrong folder.

Use Cases

  • Mailbox Cleanup: Administrators can use this cmdlet to remove unnecessary or redundant mail folders from users' mailboxes.
  • Compliance: In compliance scenarios, specific mail folders containing sensitive information can be deleted.
  • Migration: During mailbox migration, certain folders may need to be deleted as part of the cleanup process.

Possible Errors & Solutions

Error Cause Solution
Access Denied Insufficient permissions to delete the mail folder. Ensure that the account executing the cmdlet has the required permissions. Assign the necessary permissions to the account using appropriate admin roles.
MailFolderNotFound The specified MailFolderId does not exist in the user's mailbox. Verify the MailFolderId and ensure it is correct. Use Get-MgUserMailFolder to list all mail folders and confirm the folder ID.
UserNotFound The specified UserId does not exist or is incorrect. Ensure that the UserId is correct and the user exists in the directory. Validate the UserId using Get-MgUser.

Conclusion

The Remove-MgUserMailFolder cmdlet is a powerful tool for administrators to manage and clean up mail folders in user mailboxes. By understanding its syntax, usage examples, tips, use cases, and troubleshooting common errors, you can effectively utilize this cmdlet to maintain mailbox hygiene and compliance. Always double-check the parameters and use the -Confirm parameter to avoid accidental deletions.

Leverage this cmdlet to streamline your mailbox management tasks and enhance the overall efficiency of your organization's email system.



The Graph API Way - Rest API Equivalent for Remove-MgUserMailFolder

You can use the Microsoft Graph API directly via Invoke-MgGraphRequest to delete a mail folder. Below is the complete example demonstrating how to remove a user’s mail folder by ID and handle the output in a proper and consistent way using PowerShell.


Example: Remove a Mail Folder by ID
This example demonstrates how to delete a specific mail folder for a user by passing the UserId and MailFolderId.

# Define the user and mail folder ID
$userId = "user@domain.com"
$mailFolderId = "AAMkADI5AAAAAH0"

# Build the URI for the Graph API DELETE request
$uri = "https://graph.microsoft.com/v1.0/users/$userId/mailFolders/$mailFolderId"

# Make the DELETE request to remove the mail folder
try {
    $response = Invoke-MgGraphRequest -Method DELETE -Uri $uri

    # Check if the response contains a 'value' property and loop through it
    if ($response.value) {
        foreach ($item in $response.value) {
            Write-Output "Deleted Mail Folder:"
            Write-Output "ID          : $($item.id)"
            Write-Output "Display Name: $($item.displayName)"
            Write-Output "`n"
        }
    } else {
        Write-Output "Mail folder deleted successfully or no content returned in response."
    }
} catch {
    Write-Output "Failed to delete mail folder. Error: $($_.Exception.Message)"
}
                            

How It Works

  • DELETE Method: We invoke a REST call to the mailFolders endpoint with the user's ID and folder ID.
  • Error Handling: Uses try/catch to capture any failure (e.g., invalid ID, insufficient permissions).
  • Output Handling: If the API returns a value array, we loop through it and print folder details. Most DELETE operations return an empty body (204 No Content), so the fallback message confirms successful execution.

Microsoft Graph API Reference

Additional Resources:

Microsoft Graph PowerShell Module Documentation
Microsoft Graph API Documentation

Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

© Created and Maintained by LEARNIT WELL SOLUTIONS. All Rights Reserved.