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.
# 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: $_"
}
-Filter
parameter with Get-MgUser
to locate users precisely. Examples:
Get-MgUser -Filter "accountEnabled eq false"
Get-MgUser -Filter "displayName eq 'John Doe'"
Remove-MgUser
. Implement prompts or logging to prevent unintended deletions.Get-MgUser
and loop through them:
$users = Get-MgUser -Filter "accountEnabled eq false"
foreach ($user in $users) {
Remove-MgUser -UserId $user.Id
}
Remove-MgUser
after they’ve been in the Recycle Bin for 30 days or use the Azure AD portal.User.Read.All
and User.ReadWrite.All
permissions in Azure AD for these operations.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. |
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.
© m365corner.com. All Rights Reserved. Design by HTML Codex