Bulk User Deletion Using Graph PowerShell

Managing users in Microsoft 365 can sometimes require bulk operations such as deleting multiple users at once. Microsoft Graph PowerShell provides a powerful way to automate such tasks efficiently. In this article, we will walk through a script to delete multiple users in bulk using Graph PowerShell, explain how the script works, suggest possible enhancements, discuss potential errors, and provide solutions.


Script for Bulk User Deletion

First, ensure you have the Microsoft Graph PowerShell module installed and that you are authenticated. Here is the script for deleting users in bulk from a CSV file:

# Import CSV file
$csvPath = "C:\path\to\your\users_to_delete.csv"
$userList = Import-Csv -Path $csvPath

# Iterate through each user in the CSV and delete
foreach ($user in $userList) {
    try {
        # Attempt to delete the user
        Remove-MgUser -UserId $user.UserPrincipalName -Confirm:$false
        Write-Output "Successfully deleted user: $($user.UserPrincipalName)"
    } catch {
        # Catch any errors and write to the console
        Write-Error "Failed to delete user: $($user.UserPrincipalName). Error: $_"
    }
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph

How the Script Works

CSV File Import

The script starts by importing a CSV file that contains a list of user principal names (UPNs) of the users to be deleted. The CSV file should have a header named UserPrincipalName.

$csvPath = "C:\path\to\your\users_to_delete.csv"
$userList = Import-Csv -Path $csvPath

User Deletion Loop

The script then iterates through each user in the CSV file. For each user, it attempts to delete the user by their UPN using Remove-MgUser cmdlet.

foreach ($user in $userList) {
    try {
        # Attempt to delete the user
        Remove-MgUser -UserId $user.UserPrincipalName -Confirm:$false
        Write-Output "Successfully deleted user: $($user.UserPrincipalName)"
    } catch {
        # Catch any errors and write to the console
        Write-Error "Failed to delete user: $($user.UserPrincipalName). Error: $_"
    }
}

Error Handling

If an error occurs during the deletion process, it is caught and logged to the console.

Disconnect

Finally, the script disconnects from Microsoft Graph.

Disconnect-MgGraph

Enhancing the Script

Here are a few ways to enhance the script:

Logging

Implement detailed logging to a file to keep a record of which users were successfully deleted and which ones failed.

$logPath = "C:\path\to\your\deletion_log.txt"
foreach ($user in $userList) {
    try {
        Remove-MgUser -UserId $user.UserPrincipalName -Confirm:$false
        "Successfully deleted user: $($user.UserPrincipalName)" | Out-File -FilePath $logPath -Append
    } catch {
        "Failed to delete user: $($user.UserPrincipalName). Error: $_" | Out-File -FilePath $logPath -Append
    }
}

Notification

Add email notifications for success and failure cases using Send-MailMessage cmdlet.

Parallel Processing

Use parallel processing to speed up the deletion process for a large number of users.


Possible Errors and Solutions

Authentication Issues:

Solution: Ensure you are properly authenticated to Microsoft Graph with sufficient permissions (e.g., User.ReadWrite.All).

Connect-MgGraph -Scopes "User.ReadWrite.All"

User Not Found:

Solution: Ensure the UPNs in the CSV file are correct and exist in your tenant.

Permission Denied:

Solution: Make sure your account has the required admin roles and permissions.

Rate Limiting:

Solution: Implement retry logic with exponential backoff.

foreach ($user in $userList) {
    $retryCount = 0
    $maxRetries = 5
    $success = $false
    
    while (-not $success -and $retryCount -lt $maxRetries) {
        try {
            Remove-MgUser -UserId $user.UserPrincipalName -Confirm:$false
            $success = $true
            Write-Output "Successfully deleted user: $($user.UserPrincipalName)"
        } catch {
            $retryCount++
            Start-Sleep -Seconds ([math]::Pow(2, $retryCount))
            Write-Error "Retrying to delete user: $($user.UserPrincipalName). Attempt: $retryCount"
        }
    }
    
    if (-not $success) {
        Write-Error "Failed to delete user: $($user.UserPrincipalName) after $maxRetries attempts."
    }
}

Conclusion

Using Graph PowerShell for bulk user deletion is a powerful and efficient way to manage user accounts in Microsoft 365. This script provides a robust starting point for automating user deletions. By enhancing the script with logging, notifications, and error handling, you can ensure a smooth and reliable operation. Be aware of potential errors and implement solutions to handle them gracefully. Happy scripting!


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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