Managing user accounts is a critical responsibility for Microsoft 365 administrators. When employees leave or accounts are no longer needed, removing users properly is essential for security and license management.
The Remove-MgUser cmdlet allows you to delete users efficiently using Microsoft Graph PowerShell.
In this article, weβll walk through 7 practical scripts β from simple deletions to safe and conditional removals.
Connect to Microsoft Graph:
Connect-MgGraph -Scopes "User.ReadWrite.All"
Remove-MgUser -UserId "john.doe@contoso.com"
π Use case:
Quickly delete a user using their email (UPN).
Remove-MgUser -UserId "12345abc-6789-def0-1234-56789abcdef0"
π Use case:
Useful when working with scripts or API outputs that return User IDs.
Remove-MgUser -UserId "jane.doe@contoso.com" -Confirm
π Use case:
Adds an extra safety prompt before deletion.
Remove-MgUser -UserId "jane.doe@contoso.com" -WhatIf
π Use case:
Simulate deletion without actually removing the user β highly recommended before bulk operations.
Sample CSV (Users.csv)
UserPrincipalName
user1@contoso.com
user2@contoso.com
user3@contoso.com
Script
$users = Import-Csv "C:\Path\To\Users.csv"
foreach ($user in $users) {
Remove-MgUser -UserId $user.UserPrincipalName
}
π Use case:
Remove multiple users during offboarding or cleanup activities.
$user = Get-MgUser -UserId "john.doe@contoso.com" -Property "accountEnabled"
if ($user.AccountEnabled -eq $false) {
Remove-MgUser -UserId $user.Id
Write-Host "User deleted successfully."
}
else {
Write-Host "User account is still enabled. Deletion skipped."
}
π Use case:
Ensure only inactive users are deleted β safer approach for automation.
$OldUsers = Get-MgUser -All -Filter "createdDateTime lt 2023-01-01T00:00:00Z"
foreach ($User in $OldUsers) {
Remove-MgUser -UserId $User.Id -Confirm
}
π Use case:
Clean up old or unused accounts based on creation date.
| Error | Cause | solution |
| Insufficient privileges to complete the operation | Missing required permissions | Reconnect with appropriate scope: Connect-MgGraph -Scopes "User.ReadWrite.All" |
The Remove-MgUser cmdlet is a powerful tool for managing user lifecycle in Microsoft 365. From simple deletions to bulk and conditional removals, it helps administrators maintain a clean and secure environment.
Always proceed with caution β especially when performing bulk operations β and make use of -WhatIf and -Confirm to avoid accidental deletions.
Did You Know? Managing Microsoft 365 applications is even easier with automation. Try our Graph PowerShell scripts to automate tasks like generating reports, cleaning up inactive Teams, or assigning licenses efficiently.
Ready to get the most out of Microsoft 365 tools? Explore our free Microsoft 365 administration tools to simplify your administrative tasks and boost productivity.
© Your Site Name. All Rights Reserved. Design by HTML Codex