Using Get-MgUser with Remove-MgUser: Delete Microsoft 365 User Accounts

Efficient management of user accounts is a crucial aspect of Microsoft 365 administration. Two cmdlets, Get-MgUser and Remove-MgUser, can be paired to locate and delete user accounts programmatically. The Get-MgUser cmdlet allows administrators to retrieve information about users, such as their name, email, job title, and more. The Remove-MgUser cmdlet is used to delete user accounts, often as part of deprovisioning workflows. This article explores how these cmdlets work together, practical usage scenarios, tips, and troubleshooting advice to ensure smooth execution.

Usage Example: Deleting a User Account

# Step 1: Retrieve the user by email address
$userPrincipalName = "john.doe@domain.com"  # Replace with the user's UPN
$user = Get-MgUser -Filter "userPrincipalName eq '$userPrincipalName'"

if ($user -ne $null) {
    Write-Output "User Found:"
    Write-Output "Display Name: $($user.DisplayName)"
    Write-Output "User Principal Name: $($user.UserPrincipalName)"
    Write-Output "ID: $($user.Id)"
} else {
    Write-Error "User not found."
    return
}

# Step 2: Confirm deletion and remove the user
try {
    $confirm = Read-Host -Prompt "Are you sure you want to delete this user? (yes/no)"
    if ($confirm -eq "yes") {
        Remove-MgUser -UserId $user.Id 
        Write-Output "User deleted successfully."
    } else {
        Write-Output "Operation canceled."
    }
} catch {
    Write-Error "Failed to delete the user: $_"
}

Cmdlet Tips

  • Ensure Proper Filtering: Use the -Filter parameter with Get-MgUser to locate users precisely. Examples:
    Get-MgUser -Filter "accountEnabled eq false"
    Get-MgUser -Filter "displayName eq 'John Doe'"
  • Avoid Accidental Deletions: Always confirm the user’s details before running Remove-MgUser. Implement prompts or logging to prevent unintended deletions.
  • Use Bulk Operations for Efficiency: For cleaning up multiple accounts, retrieve a list of users with Get-MgUser and loop through them:
    $users = Get-MgUser -Filter "accountEnabled eq false"
    foreach ($user in $users) {
        Remove-MgUser -UserId $user.Id 
    }
  • Soft vs. Hard Deletions: By default, deleting a user moves them to the Recycle Bin (soft delete). To hard delete a user, use Remove-MgUser after they’ve been in the Recycle Bin for 30 days or use the Azure AD portal.
  • Assign Delegated Permissions: Ensure you have User.Read.All and User.ReadWrite.All permissions in Azure AD for these operations.

Use Cases

  1. User Offboarding: Automatically delete user accounts during offboarding to prevent unauthorized access.
  2. Inactive Account Cleanup: Remove inactive or disabled accounts to optimize licensing costs.
  3. Compliance and Security: Ensure accounts of former employees or contractors are deleted to meet compliance requirements.
  4. Bulk Deletion: Clean up old or unused test accounts during tenant restructuring or migration.

Possible Errors & Solutions

Error Message Cause Solution
User Not Found Invalid or non-existent UserId or filter Verify the UserPrincipalName or Id and ensure the account exists.
Access Denied Insufficient permissions Grant appropriate permissions (User.Read.All and User.ReadWrite.All).
User Is a Manager of an Active Group Attempting to delete a user who manages groups Reassign group management roles before deletion.
Too Many Requests API throttling due to bulk operations Implement retry logic with pauses to handle throttling.
Soft Deleted User Already Exists User is already soft deleted Use the Azure AD portal or scripts to hard delete the user.

Conclusion

Pairing Get-MgUser and Remove-MgUser provides a powerful way to manage user accounts in Microsoft 365. Whether offboarding employees, cleaning up inactive accounts, or performing bulk deletions, these cmdlets enable efficient and precise management.

Suggested Reading

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