This article explains how you can delete Microsoft 365 users using Graph PowerShell with the help of Remove-MgUser cmdlet.
To delete a single user, you can pass in the UserPrincipalName of the user to be deleted as the parameter to -UserId. Alternatively, you can also pass in the UserId. Get-MgUser is the cmdlet that helps you get the User IDs.
# Ensure you are connected to Microsoft Graph
Connect-MgGraph -Scopes "User.ReadWrite.All"
# Define the user principal name of the user you want to delete
$userPrincipalName = "user@example.com"
# Soft delete the user
Remove-MgUser -UserId $userPrincipalName
Write-Output "User $userPrincipalName has been soft deleted."
You can delete multiple users contained in a PowerShell array by looping through the array items [users] and executing the Remove-MgUser cmdlet for each of the items within the array.
# Define the array of user principal names
$users = @("testuser2@7xh7fj.onmicrosoft.com", "testuser3@7xh7fj.onmicrosoft.com")
# Loop through each user and delete
foreach ($user in $users) {
try {
Remove-MgUser -UserId $user
Write-Output "deleted user: $user"
} catch {
Write-Output "Failed to delete user: $user. Error: $_"
}
}
You can also import users from CSV file, loop through them, and execute Remove-MgUser cmdlet for each of the users so that they get deleted.Your CSV file should contain either the UserId or UserPrincipalName as the CSV header and the corresponding values.
# Import required module
Import-Module Microsoft.Graph.Identity.DirectoryManagement
# Get the list of users from a CSV file
$users = Import-Csv -Path "C:\path\to\your\file.csv"
# Loop through each user and soft delete
foreach ($user in $users) {
Remove-MgUser -UserId $user.UserPrincipalName -Force
Write-Output "Soft deleted user: $($user.UserPrincipalName)"
}
Enhancing the script for deleting Microsoft 365 groups based on a specific creation date can be approached from several angles, focusing on adding more functionality, improving user experience, and ensuring better safety and compliance. Here are some suggestions:
These enhancements can help ensure that the script is not only effective at deleting user accounts but also compliant with organizational policies and capable of providing detailed logs for forensic or compliance purposes.
© m365corner.com. All Rights Reserved. Design by HTML Codex