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

Managing user accounts is a critical responsibility for Microsoft 365 administrators. Pairing Get-MgUser and Remove-MgUser allows administrators to identify users and remove them from the tenant when necessary. This article explores the effective use of these cmdlets, providing practical examples, tips, and troubleshooting advice.

The Get-MgUser cmdlet retrieves detailed information about user accounts in Microsoft Entra ID (Azure AD), such as displayName, userPrincipalName, accountEnabled, and more. The Remove-MgUser cmdlet enables administrators to delete users, typically during offboarding or for maintaining a clean directory. Combining these cmdlets ensures that the right accounts are identified and removed accurately.

Usage Example: Identifying and Removing a User

Here’s how to retrieve a user’s details and remove them from the tenant:


# Step 1: Retrieve the user's details
$userId = "john.doe@domain.com"  # Replace with the user's UPN or ObjectId

try {
    $user = Get-MgUser -UserId $userId -Property "Id, DisplayName, UserPrincipalName, AccountEnabled"
    if ($user) {
        Write-Output "User Found:"
        Write-Output "Display Name: $($user.DisplayName)"
        Write-Output "UPN: $($user.UserPrincipalName)"
        Write-Output "Account Enabled: $($user.AccountEnabled)"
    } else {
        Write-Error "User not found."
        return
    }
} catch {
    Write-Error "Failed to retrieve user details: $_"
}

# Step 2: Remove the user
try {
    Remove-MgUser -UserId $user.Id 
    Write-Output "User '$($user.DisplayName)' has been removed successfully."
} catch {
    Write-Error "Failed to remove user: $_"
}
                            

Cmdlet Tips

  • Verify User Details Before Deletion: Use Get-MgUser to ensure you’re deleting the correct user by verifying properties like displayName and userPrincipalName.
  • Use Filters for Efficiency: Use the -Filter parameter with Get-MgUser to locate users based on criteria such as department or account status:
    Get-MgUser -Filter "department eq 'Sales'"
  • Bulk User Deletion: Delete multiple users by looping through a list of user IDs or applying a filter:
    $users = Get-MgUser -Filter "accountEnabled eq false"
    foreach ($user in $users) {
        Remove-MgUser -UserId $user.Id 
    }
  • Soft Delete Behavior: By default, Remove-MgUser soft-deletes the user. They can be restored within 30 days using Restore-MgDeletedUser:
    Restore-MgDeletedUser -UserId "deleted-user-id"
  • Hard Delete: To permanently delete a user, soft-delete them first, then use Remove-MgDeletedUser to purge:
    Remove-MgDeletedUser -UserId "deleted-user-id"

Use Cases

  1. Offboarding Employees: Automate the removal of user accounts during offboarding workflows to maintain a secure and organized tenant.
  2. Cleaning Up Disabled Accounts: Identify and delete accounts that are no longer active, ensuring the directory remains clean and up-to-date.
  3. Compliance and Security: Remove accounts immediately in response to security incidents or to comply with organizational policies.
  4. Tenant Optimization: Identify stale accounts, such as test users or unused guest accounts, and remove them to optimize tenant management.
  5. Bulk User Management: Handle user removal at scale during organizational changes, such as mergers or downsizing.

Possible Errors & Solutions

Error Message Cause Solution
User Not Found Incorrect or non-existent UserId Verify the user’s UPN or ObjectId with Get-MgUser.
Access Denied Insufficient permissions Assign User.ReadWrite.All or Directory.ReadWrite.All permissions.
Cannot Delete Active User Attempt to delete an account still in use Ensure the account is disabled before deletion or use the -Force flag.
Too Many Requests API throttling due to bulk operations Implement a delay between requests or use batching for large operations.
Cannot Hard Delete Attempt to permanently delete a user directly Soft-delete the user first, then use Remove-MgDeletedUser.

Conclusion

Pairing Get-MgUser and Remove-MgUser provides administrators with a precise and reliable way to manage user accounts in Microsoft 365. Whether offboarding employees, cleaning up stale accounts, or responding to security incidents, these cmdlets streamline user management workflows and ensure a secure and efficient environment.

By integrating these cmdlets into your administrative processes, you can maintain a well-organized directory while adhering to organizational policies and compliance requirements.

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