Skip to content

Remove Azure AD users with Microsoft Graph PowerShell

When you remove an Azure AD user account, it will remain in the recycle bin for 30 days. After these 30 days, Azure AD automatically deletes the user account. We will show you how to remove and permanently delete Azure AD users with Remove-MgUser and Remove-MgDirectoryDeletedItem cmdlets. In this article, you will learn how to remove Azure AD users with Microsoft Graph PowerShell.

Remove-AzureADUser and Remove-MsolUser deprecated

Microsoft announced announced the Azure AD, Azure AD Preview, and MS Online PowerShell modules will be deprecated on March 30, 2024. You need to replace the Remove-AzureADUser and Remove-MsolUser cmdlets with the new Microsoft Graph PowerShell cmdlets.

We will show you how to delete Azure AD users with Microsoft Graph PowerShell:

  1. Remove (soft-delete) an Azure AD user account to the recycle bin
  2. Permanently delete (hard-delete) an Azure AD user account from the recycle bin

Manage Azure AD users with Microsoft Graph PowerShell

We created specific articles to manage Azure AD users with Microsoft Graph PowerShell:

Connect to Microsoft Graph PowerShell

Before you start, you must install the Microsoft Graph PowerShell module, including the Microsoft Graph Beta module.

Run the below command to install the Microsoft Graph module.

Install-Module Microsoft.Graph -Force
Install-Module Microsoft.Graph.Beta -AllowClobber -Force

You also need to connect to MS Graph with the below permissions.

Connect-MgGraph -Scopes "User.Read.All", "User.ReadWrite.All", "Directory.AccessAsUser.All", "Directory.ReadWrite.All"

Now you are all set to use the Microsoft Graph PowerShell commands.

Bulk export list soft deleted Azure AD users to CSV

You can get a list of all the Azure AD deleted users in the recycle bin. The below script will show the list in a grid view and save a CSV file to the temp folder. Create a temp folder in your (C:) drive if you don’t have one.

Run the below PowerShell script to bulk export a list of Azure AD users to a CSV file.

# Retrieve deleted directory items
$DeletedItems = Get-MgDirectoryDeletedItem -DirectoryObjectId Microsoft.Graph.User -Property 'Id', 'displayName', 'deletedDateTime', 'userType'

# Check if there are no deleted accounts
if ($DeletedItems.AdditionalProperties['value'].count -eq 0) {
    Write-Host "No deleted accounts found - exiting"
}
else {
    # Create an array to store the report
    $Report = @()

    # Loop through the deleted items
    foreach ($Item in $DeletedItems.AdditionalProperties['value']) {
        $DeletedDate = Get-Date($Item['deletedDateTime'])
        $DaysSinceDeletion = (New-TimeSpan $DeletedDate).Days

        # Create a custom object for each item and add it to the report
        $ReportLine = [PSCustomObject]@{
            UserId                = $Item['id']
            Name                  = $Item['displayName']
            Deleted               = $DeletedDate
            'Days Since Deletion' = $DaysSinceDeletion
            Type                  = $Item['userType']
        }
        $Report += $ReportLine
    }

    # Sort and export the report by 'Days Since Deletion'
    $Report | Sort-Object 'Days Since Deletion' | select UserId, Name, Deleted, 'Days Since Deletion' | Out-GridView
    $Report | Sort-Object 'Days Since Deletion' | Export-CSV -Encoding UTF8 -NoTypeInformation "C:\temp\AzureDeletedUsers.csv"
}

The Out-GridView appears after the script finishes.

Remove Azure AD users with Microsoft Graph PowerShell out grid view

You will find the CSV file in the C:\temp folder. Open the CSV file with an application like Microsoft Excel to see the results.

Delete Azure AD user with Microsoft Graph PowerShell export CSV file

Soft delete Azure AD user account

You can always delete an Azure AD user, but this account will move to the recycle bin. The deleted user will remain in the Azure AD recycle bin for 30 days. We will show you how to remove any Azure AD user account in three methods:

  • Soft delete a single Azure AD user account
  • Soft delete multiple Azure AD users with CSV
  • Bulk soft delete all Azure AD users

Remove-MgUser Azure AD user

To soft-delete an Azure AD user account, use the Remove-MgUser cmdlet with Microsoft Graph PowerShell. In our example, we want to delete the user account Megan.Jones@m365info.com.

Run the below PowerShell command example to remove the user account.

Remove-MgUser -UserId "Megan.Jones@m365info.com"

You can also use the user ID of the account.

Remove-MgUser -UserId "2b8f4e12-46f1-45ef-bcac-0d5ab84c819c"

You will not see a PowerShell output. It will remove the user account to the recycle bin, where it remains for 30 days.

Soft delete multiple accounts from CSV

You can soft delete multiple Azure AD users with a CSV file.

Create a single CSV file with Notepad or Microsoft Excel and type the following data:

  1. Type UserPrincipalName at top
  2. List the Azure AD users

See the below CSV file example.

  1. Create the folder temp if you don’t have it already in the (C:) drive
  2. Name the file Remove.csv
  3. Save as type CSV (Comma delimited)(*.csv)
  4. Click Save
Use Remove-MgUser with Microsoft Graph PowerShell csv file
  1. Run the below PowerShell script
$users = Import-Csv -Path "C:\temp\Remove.csv"

foreach ($user in $users) {
    $userPrincipalName = $user.UserPrincipalName
    $userExists = $null

    try {
        # Check if the user exists using the Microsoft Graph API
        $userExists = Get-MgUser -UserId $userPrincipalName -ErrorAction Stop

        # If the user exists, attempt to remove them
        Remove-MgUser -UserId $userPrincipalName -ErrorAction Stop #-WhatIf

        Write-Host "Account $userPrincipalName has been deleted." -ForegroundColor Green
    }
    catch {
        if ($userExists -eq $null) {
            # User doesn't exist
            Write-Host "Account $userPrincipalName not found in Azure AD users." -ForegroundColor Yellow
        }
        else {
            # Error occurred during removal
            Write-Host "Account $userPrincipalName couldn't be deleted." -ForegroundColor Cyan
        }
    }
}

The PowerShell output shows the following result.

Account Chris.Lucas@m365info.com has been deleted.
Account George.Wilson@m365info.com has been deleted.
Account Ken.Walker@m365info.com has been deleted.
Account Laura.Terry@m365info.com has been deleted.
Account Unknown@m365info.com not found in Azure AD users.

It will delete the Azure AD accounts from the CSV file if they exist in your Azure tenant.

Bulk soft delete all Azure AD users

You can soft delete all the Azure AD users, which will remove them to the recycle bin.

Run the below PowerShell script.

$users = Get-MgUser -All

foreach ($user in $users) {
    $displayName = $user.DisplayName
    Remove-MgUser -UserId $user.UserPrincipalName #-WhatIf
    Write-Host "Deleted user: $($displayName)" -ForegroundColor Green
}

The PowerShell script will automatically remove all the Azure AD users. You will get the below error because the admin can’t delete itself.

Error: Remove-MgUser : The principal performing this request cannot delete itself.

Hard delete removed Azure AD user account

You can only hard delete an Azure AD user if the account is still in the recycle bin. This way, you will permanently delete an Azure AD account. We will show you how to hard delete an already removed Azure AD user account in three methods:

  • Hard delete a single Azure AD user account
  • Hard delete multiple Azure AD users with CSV
  • Bulk hard delete all Azure AD users

Remove-MgDirectoryDeletedItem Azure AD user

When you already deleted a user account, you don’t have to wait 30 days for it to be deleted. You can force hard delete an Azure AD user account from the recycle bin. We must use the Remove-MgDirectoryDeletedItem cmdlet to delete a recently deleted Azure AD account.

Note: Once you hard delete a user, there is no opportunity to restore this user or any data associated with that user.

In our example, we want to delete the user account Jill.Bates@m365info.com permanently. Here again, you must use the Object ID number.

Run the below PowerShell command example.

Remove-MgDirectoryDeletedItem -DirectoryObjectId "a9532b30-4edb-4b66-a3b0-6ac972a6065b"

You will not get an output in PowerShell because it automatically deletes the user account permanently.

Hard delete multiple Azure AD users from CSV

To hard delete a few Azure AD users from the recycle bin, you need to create a CSV file.

Note: When you hard delete a user account, you must type the ID with the hyphens (-), or the PowerShell script will not work.

Create a CSV file with 2 columns:

  1. Type ID at the top of column A
  2. Type UserPrincipalName at the top of column B
  3. List the ID number, including hyphens (-) of each user
  4. List the UPN for each user

See the below CSV file example.

Use Remove-MgDirectoryDeletedItem to hard delete users
  1. Create the folder temp if you don’t have it already in the (C:) drive
  2. Name the file Delete.csv
  3. Save as type CSV UTF-8 (Comma delimited)(*.csv)
  4. Click Save
Use Remove-MgDirectoryDeletedItem to hard delete users csv file
  1. Run the below PowerShell script to hard delete multiple Azure AD users
# Retrieve deleted directory items
$DeletedItems = Get-MgDirectoryDeletedItem -DirectoryObjectId Microsoft.Graph.User -Property 'Id', 'displayName'

# Import the CSV file with user IDs
$UserIds = Import-Csv -Path "C:\temp\Delete.csv"

foreach ($UserId in $UserIds) {
    $Id = $UserId.ID

    # Check if the user ID exists in the deleted items
    $DeletedUser = $DeletedItems.AdditionalProperties['value'] | Where-Object { $_['id'] -eq $Id }

    if ($DeletedUser -ne $null) {
        # Hard delete the user by ID
        Remove-MgDirectoryDeletedItem -DirectoryObjectId $Id #-WhatIf
        Write-Host "Hard deleted user $($DeletedUser['displayName']) with ID: $Id" -ForegroundColor Red
    }
    else {
        Write-Host "User with ID $Id not found in deleted items." -ForegroundColor Yellow
    }
}

Write-Host "Hard deletion process completed." -ForegroundColor Cyan

The PowerShell output result example.

Hard deleted user Chris Lucas with ID: fa956d8c-87df-4cd4-ac2a-ac1f3d7cac8b
Hard deleted user Ken Walker with ID: 12eefbb2-e5f4-4eec-bd18-df7ca2f1ee6b
Hard deleted user Megan Jones with ID: 2b8f4e12-46f1-45ef-bcac-0d5ab84c819c
User with ID 954b27cf-8401-420b-bbd2-7f70903c0707 not found in deleted items.
Hard deletion process completed.

Bulk hard delete all Azure AD users

You can hard delete all Azure AD users from the recycle bin.

Note: This will permanently delete the user account and all its details. You can’t restore Azure AD users after this because it will empty the recycle bin.

Run the PowerShell script.

# Retrieve deleted directory items
$DeletedItems = Get-MgDirectoryDeletedItem -DirectoryObjectId Microsoft.Graph.User -Property 'Id', 'displayName'

# Check if there are no deleted accounts
if ($DeletedItems.AdditionalProperties['value'].count -eq 0) {
    Write-Host "No deleted accounts found in recycle bin." -ForegroundColor Cyan
}
else {
    # Hard delete removed users
    foreach ($Item in $DeletedItems.AdditionalProperties['value']) {
        # Hard delete the user by ID
        Remove-MgDirectoryDeletedItem -DirectoryObjectId $Item['id'] #-WhatIf
        Write-Host "Hard deleted user $($Item['displayName'])" -ForegroundColor Green
    }
    
    Write-Host "Hard delete removal process completed." -ForegroundColor Cyan
}

It will hard delete all the users in the Azure AD recycle bin. See the below PowerShell output result example.

Hard deleted user George Wilson
Hard deleted user Jill Bates
Hard deleted user Julia Wood
Hard deleted user Kelly Test
Hard deleted Laura Terry
Hard deleted user New User
Hard deleted user Stephen Hunter
Hard delete removal process completed.

You successfully managed to soft and hard delete Azure AD users with MS Graph PowerShell.

Read more: Manage Microsoft 365 users recycle bin »

Conclusion

You learned how to remove Azure AD users with Microsoft Graph PowerShell. Use the Remove-MgUser cmdlet to delete a single or multiple Azure AD user accounts to the recycle bin. Suppose you want to permanently delete the Azure AD users from the recycle bin, use the Remove-MgDirectoryDeletedItem cmdlet.

Did you enjoy this article? You may also like Force delete Microsoft 365 mailbox with PowerShell. Don’t forget to follow us and share this article.

o365info Team

o365info Team

This article was written by our team of experienced IT architects, consultants, and engineers.

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *