Friday, November 15, 2024

Delete AzureAD user

# Import the AzureAD module
Import-Module AzureAD

# Connect to Azure AD
Write-Host "Connecting to Azure AD..."
Connect-AzureAD

# Define the path to the CSV file
$csvPath = "C:\HRM users License Report\cleanup\DisabledAccont12Nov2024.csv"

# Import the CSV file
Write-Host "Importing user list from CSV..."
$users = Import-Csv -Path $csvPath

# Loop through each user in the CSV file and delete the account
Write-Host "Starting user deletion process..."

foreach ($user in $users) {
    $userPrincipalName = $user.UserPrincipalName  # Adjust the column name if needed

    try {
        # Retrieve the user by UserPrincipalName using the filter approach
        $azureADUser = Get-AzureADUser -Filter "UserPrincipalName eq '$userPrincipalName'"
        
        if ($azureADUser) {
            # Delete the user using ObjectId
            Write-Host "Attempting to delete user: $userPrincipalName"
            Remove-AzureADUser -ObjectId $azureADUser.ObjectId
            Write-Host "Deleted user: $userPrincipalName" -ForegroundColor Green
        }
        else {
            Write-Host "User not found: $userPrincipalName" -ForegroundColor Yellow
        }
    }
    catch {
        Write-Host "Failed to delete user: $userPrincipalName. Error: $_" -ForegroundColor Red
    }
}

Write-Host "User deletion process completed."

No comments:

Post a Comment

HTML

Script:

JS