Remove-MgUser: How to Delete Microsoft 365 Users with Graph PowerShell

Learn how to use Remove-MgUser cmdlet in Microsoft Graph PowerShell to delete users from your Microsoft 365 tenant. This guide covers single and bulk user deletion, troubleshooting common errors, and best practices for user account cleanup.

The Remove-MgUser cmdlet is a powerful tool for administrators managing Microsoft 365 environments. This cmdlet allows you to remove user accounts from your Azure Active Directory (AAD). In this article, we'll cover the prerequisites for using the Remove-MgUser cmdlet, explain its syntax and parameters, provide various usage examples, offer some tips, and address common errors and their solutions.


Prerequisites

  • Install Microsoft Graph PowerShell Module: Ensure the Microsoft Graph PowerShell module is installed. If not, install it using the following command:
    Install-Module Microsoft.Graph
  • Microsoft 365 Administrator Role: You should possess either global administrator or user administrator role.
  • Graph API Permission: You must have the "User.ReadWrite.All" Graph API permission.
  • Connect to Microsoft Graph: Authenticate and connect to your Microsoft Graph environment by running the following command:
    Connect-MgGraph -Scopes "User.ReadWrite.All"

Cmdlet Syntax

Remove-MgUser -UserId <String> [-WhatIf] [-Confirm] [<CommonParameters>]
  • -UserId: (Required) The unique identifier (ID) or User Principal Name (UPN) of the user to be removed.
  • -WhatIf: (Optional) Shows what would happen if the cmdlet runs. The cmdlet is not executed.
  • -Confirm: (Optional) Prompts for confirmation before executing the cmdlet.
  • <CommonParameters>: This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable.

Usage Examples


Remove a User by UPN

Passing UserPrincipalName to -UserId parameter to delete the user.

Remove-MgUser -UserId "john.doe@contoso.com"

Remove a User by User ID

Passing UserId to -UserId parameter to delete the user.

Remove-MgUser -UserId "12345abc-6789-def0-1234-56789abcdef0"

Remove a User with Confirmation

Using -Confirm parameter to confirm the user deletion operation before the user gets deleted.

Remove-MgUser -UserId "jane.doe@contoso.com" -Confirm
PowerShell command using Remove-MgUser with -Confirm parameter to delete a user account.

Preview User Removal

Using -WhatIf parameter to preview user deletion operation before the user gets deleted.

Remove-MgUser -UserId "jane.doe@contoso.com" -WhatIf
PowerShell command using Remove-MgUser with -WhatIf parameter to preview user deletion

Bulk Remove Users from a CSV File

Using Import-CSV cmdlet to import users from CSV file and delete them. The CSV file should contain UserPrincipalName header with corresponding userprincipalname values.

$users = Import-Csv "C:\Path\To\Users.csv"
foreach ($user in $users) {
    Remove-MgUser -UserId $user.UserPrincipalName 
}

Cmdlet Tips

  • Use the -WhatIf Parameter: Before executing the cmdlet, use the -WhatIf parameter to see what changes will be made without actually removing the user.
  • Bulk Removal: To remove multiple users, you can combine this cmdlet with the Get-MgUser cmdlet and a loop or pipeline.
  • Backup User Data Before Removal:
    • Tip: Before removing a user, consider backing up their data, such as emails, OneDrive files, and other critical information, using appropriate cmdlets (Export-MgUserMail, Export-MgUserOneDriveContent).
    • Benefit: Ensures that important data is not lost during the removal process and can be accessed if needed after the account is deleted.
  • Use Soft-Delete for Safety:
    • Tip: When removing users, consider using the soft-delete option, where accounts are placed in a "Deleted" state but can be restored within a certain period.
    • Benefit: By default, Remove-MgUser performs a soft-delete, retaining the account for a configurable period (usually 30 days) before permanent deletion. If you want to recover the account before permanent deletion happens, run the following command: Restore-MgUser -UserId "terminateduser@domain.com"

Use Cases


  1. Offboarding Employees:
    • Scenario: When an employee leaves the organization, their account must be removed from Microsoft 365 to prevent unauthorized access.
    • Implementation: Use Remove-MgUser to delete the user's account, ensuring that all associated licenses, group memberships, and access rights are also revoked.
    • Benefit: Protects the organization by preventing former employees from accessing company resources after they leave.

  2. Removing Inactive or Dormant Accounts:
    • Scenario: Over time, some user accounts may become inactive or dormant, either due to long-term leave, project completion, or other reasons.
    • Implementation: Use Remove-MgUser to regularly clean up inactive accounts from the directory, based on criteria like last sign-in date or account activity.
    • Benefit: Keeps the directory organized, reduces licensing costs, and minimizes security risks associated with unused accounts.

  3. Compliance and Security Audits:
    • Scenario: During security audits or compliance checks, certain user accounts may need to be removed to ensure adherence to regulatory standards.
    • Implementation: Use Remove-MgUser to delete accounts that do not comply with security policies or that pose a potential risk.
    • Benefit: Helps maintain a secure and compliant environment, ensuring that only authorized users have access to sensitive data and systems.

  4. Bulk Deletion of Temporary Accounts:
    • Scenario: Temporary accounts created for contractors, interns, or project-based work need to be deleted after the project or contract ends.
    • Implementation: Use Remove-MgUser in combination with a script that reads from a list of user IDs to delete multiple accounts at once.
    • Benefit: Automates the cleanup process, ensuring that temporary accounts are promptly removed, reducing potential security vulnerabilities.

Common Errors and Solutions

Error: Insufficient Permissions

Issue: Authorization_RequestDenied

Solution: Ensure you have the necessary permissions to remove users. Verify you are signed in with an account that has the User.ReadWrite.All scope and is a Global Administrator or User Administrator in Azure AD.

Error: User Not Found

Issue: Resource 'user_id' does not exist or one of its queried reference-property objects are not present.

Solution: Verify the UserId is correct. Use the Get-MgUser cmdlet to confirm the user exists:

Get-MgUser -UserId "john.doe@contoso.com"


Frequently Asked Questions

What is Remove-MgUser used for?

Remove-MgUser is a Microsoft Graph PowerShell cmdlet used to delete user accounts from a Microsoft 365 tenant. It is commonly used to manage and clean up inactive or unnecessary accounts.

How can I delete multiple users at once using Remove-MgUser?

Prepare a CSV file with a column for UserPrincipalName or ObjectId and use this script for bulk deletion:


    $Users = Import-Csv -Path "C:\Path\To\File.csv"
    foreach ($User in $Users) {
        Remove-MgUser -UserId (Get-MgUser -UserPrincipalName $User.UserPrincipalName).Id -Force
    }

What permissions are required to use Remove-MgUser?

To use Remove-MgUser, the account must have one of the following permissions:

  • Delegated Permissions: User.ReadWrite.All
  • Application Permissions: User.ReadWrite.All

How can I verify that a user has been successfully deleted?

After executing the Remove-MgUser cmdlet, you can confirm the deletion by attempting to retrieve the user's details:

Get-MgUser -UserId "user@domain.com"

If the user has been successfully deleted, this command will return an error indicating that the resource does not exist.

Can I restore a user after deletion, and what is the timeframe for restoration?

Yes, when a user is deleted using the Remove-MgUser cmdlet, the account is moved to a temporary container (soft-deleted) and can be restored within 30 days. To restore a deleted user, use the Restore-MgUser cmdlet

Restore-MgUser -UserId "user@domain.com"

After 30 days, if not restored, the user object is permanently deleted, and their assigned resources are freed.

How can I handle errors indicating insufficient permissions when using Remove-MgUser?

If you encounter an "Insufficient privileges to complete the operation" error, it indicates that your account lacks the necessary permissions to delete users. Ensure that you are signed in with an account that has the User.ReadWrite.All scope and is assigned either the Global Administrator or User Administrator role in Azure Active Directory.

Is it possible to permanently delete a user immediately without waiting for the 30-day retention period?

Yes, to permanently delete a user without waiting for the 30-day retention period, you must first soft-delete the user using Remove-MgUser and then permanently delete the user from the deleted items container:

#Soft-delete the user 
Remove-MgUser -UserId "user@domain.com"

Remove-MgUser -UserId "user@domain.com"

# Permanently delete the user
Remove-MgDirectoryDeletedItem -DirectoryObjectId "user_object_id"

Conclusion

The Remove-MgUser cmdlet is essential for managing user accounts in Azure AD. By understanding its syntax, parameters, and usage, you can effectively remove user accounts as needed. Always ensure you have the proper permissions and use caution, especially with the -Confirm parameter, to avoid unintentional deletions. For bulk operations, consider using scripts to streamline the process. With these guidelines, you'll be well-equipped to manage user removals in your Microsoft 365 environment.

Suggested Reading

© m365corner.com. All Rights Reserved. Design by HTML Codex