当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 Microsoft Graph PowerShell 删除 Azure AD 用户

作者:精品下载站 日期:2024-12-14 09:14:50 浏览:15 分类:玩电脑

使用 Microsoft Graph PowerShell 删除 Azure AD 用户


删除 Azure AD 用户帐户后,它将在回收站中保留 30 天。 30 天后,Azure AD 会自动删除用户帐户。我们将向您展示如何使用Remove-MgUser 和Remove-MgDirectoryDeletedItem cmdlet 删除并永久删除Azure AD 用户。在本文中,你将了解如何使用 Microsoft Graph PowerShell 删除 Azure AD 用户。

已弃用删除-AzureADUser 和删除-MsolUser

Microsoft 宣布 Azure AD、Azure AD Preview 和 MS Online PowerShell 模块将于 2024 年 3 月 30 日弃用。您需要替换 Remove-AzureADUserRemove-MsolUser 具有新 Microsoft Graph PowerShell cmdlet 的 cmdlet。

我们将向您展示如何使用 Microsoft Graph PowerShell 删除 Azure AD 用户:

  1. 将 Azure AD 用户帐户删除(软删除)到回收站
  2. 从回收站永久删除(硬删除)Azure AD 用户帐户

使用 Microsoft Graph PowerShell 管理 Azure AD 用户

我们创建了具体的文章来使用 Microsoft Graph PowerShell 管理 Azure AD 用户:

  • 使用 Microsoft Graph PowerShell 导出 Azure AD 用户
  • 使用 Microsoft Graph PowerShell 删除 Azure AD 用户(本文)
  • 使用 Microsoft Graph PowerShell 恢复 Azure AD 用户
  • 使用 Microsoft Graph PowerShell 更新 Azure AD 用户

连接到 Microsoft Graph PowerShell

在开始之前,必须安装 Microsoft Graph PowerShell 模块,包括 Microsoft Graph Beta 模块。

运行以下命令来安装 Microsoft Graph 模块。

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

您还需要使用以下权限连接到 MS Graph。

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

现在您已准备好使用 Microsoft Graph PowerShell 命令。

将软删除的 Azure AD 用户列表批量导出到 CSV

您可以获取回收站中所有 Azure AD 已删除用户的列表。下面的脚本将在网格视图中显示列表,并将 CSV 文件保存到temp文件夹中。如果您没有 (C:) 驱动器,请创建一个 temp 文件夹。

运行以下 PowerShell 脚本将 Azure AD 用户列表批量导出到 CSV 文件。

# 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"
}

脚本完成后将出现 Out-GridView。

[玩转系统] 使用 Microsoft Graph PowerShell 删除 Azure AD 用户

您将在 C:\temp 文件夹中找到 CSV 文件。使用 Microsoft Excel 等应用程序打开 CSV 文件以查看结果。

[玩转系统] 使用 Microsoft Graph PowerShell 删除 Azure AD 用户

软删除 Azure AD 用户帐户

您始终可以删除 Azure AD 用户,但此帐户将移至回收站。已删除的用户将在 Azure AD 回收站中保留 30 天。我们将向您展示如何通过三种方法删除任何 Azure AD 用户帐户:

  • 软删除单个 Azure AD 用户帐户
  • 使用 CSV 软删除多个 Azure AD 用户
  • 批量软删除所有 Azure AD 用户

删除-MgUser Azure AD 用户

若要软删除 Azure AD 用户帐户,请结合使用 Remove-MgUser cmdlet 和 Microsoft Graph PowerShell。在我们的示例中,我们要删除用户帐户 [email protected]

运行以下 PowerShell 命令示例以删除用户帐户。

Remove-MgUser -UserId "[email protected]"

您还可以使用帐户的用户 ID

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

您将看不到 PowerShell 输出。它将把用户帐户删除到回收站,并保留 30 天。

从 CSV 中软删除多个帐户

您可以使用 CSV 文件软删除多个 Azure AD 用户。

使用记事本Microsoft Excel创建单个 CSV 文件并输入以下数据:

  1. 在顶部输入UserPrincipalName
  2. 列出 Azure AD用户

请参阅下面的 CSV 文件示例。

[玩转系统] 使用 Microsoft Graph PowerShell 删除 Azure AD 用户

  1. 如果 (C:) 驱动器中还没有文件夹 temp,请创建该文件夹
  2. 将文件命名为Remove.csv
  3. 保存类型为CSV(逗号分隔)(*.csv)
  4. 点击保存

[玩转系统] 使用 Microsoft Graph PowerShell 删除 Azure AD 用户

  1. 运行以下 PowerShell 脚本
$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
        }
    }
}

PowerShell 输出显示以下结果。

Account [email protected] has been deleted.
Account [email protected] has been deleted.
Account [email protected] has been deleted.
Account [email protected] has been deleted.
Account [email protected] not found in Azure AD users.

如果 Azure AD 帐户存在于 Azure 租户中,它将从 CSV 文件中删除它们。

批量软删除所有 Azure AD 用户

您可以软删除所有 Azure AD 用户,这会将它们删除到回收站。

运行以下 PowerShell 脚本。

$users = Get-MgUser -All

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

PowerShell 脚本将自动删除所有 Azure AD 用户。您将收到以下错误,因为管理员无法删除自身。

错误:Remove-MgUser:执行此请求的主体无法删除自身。

硬删除已删除的 Azure AD 用户帐户

仅当帐户仍位于回收站中时,才能硬删除 Azure AD 用户。这样,您将永久删除 Azure AD 帐户。我们将向您展示如何通过三种方法硬删除已删除的 Azure AD 用户帐户:

  • 硬删除单个 Azure AD 用户帐户
  • 使用 CSV 硬删除多个 Azure AD 用户
  • 批量硬删除所有 Azure AD 用户

删除-MgDirectoryDeletedItem Azure AD 用户

如果您已经删除了用户帐户,则无需等待 30 天即可删除。您可以从回收站强制硬删除 Azure AD 用户帐户。我们必须使用Remove-MgDirectoryDeletedItem cmdlet 来删除最近删除的Azure AD 帐户。

注意:硬删除用户后,将无法恢复该用户或与该用户关联的任何数据。

在我们的示例中,我们想要永久删除用户帐户 [email protected]。同样,您必须使用对象 ID 编号。

运行以下 PowerShell 命令示例。

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

您不会在 PowerShell 中获得输出,因为它会自动永久删除用户帐户。

从 CSV 中硬删除多个 Azure AD 用户

要从回收站中硬删除一些 Azure AD 用户,您需要创建一个 CSV 文件。

注意:硬删除用户帐户时,必须输入带有连字符 (-) 的ID,否则 PowerShell 脚本将无法运行。

创建一个包含 2 列的 CSV 文件:

  1. 在 A 列顶部输入 ID
  2. 在 B 列顶部输入 UserPrincipalName
  3. 列出每个用户的ID号,包括连字符(-)
  4. 列出每个用户的 UPN

请参阅下面的 CSV 文件示例。

[玩转系统] 使用 Microsoft Graph PowerShell 删除 Azure AD 用户

  1. 如果 (C:) 驱动器中还没有文件夹 temp,请创建该文件夹
  2. 将文件命名为Delete.csv
  3. 保存类型为 CSV UTF-8(逗号分隔)(*.csv)
  4. 点击保存

[玩转系统] 使用 Microsoft Graph PowerShell 删除 Azure AD 用户

  1. 运行以下 PowerShell 脚本以硬删除多个 Azure AD 用户
# 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

PowerShell 输出结果示例。

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.

批量硬删除所有 Azure AD 用户

您可以从回收站中硬删除所有 Azure AD 用户。

注意:这将永久删除用户帐户及其所有详细信息。此后您无法恢复 Azure AD 用户,因为这会清空回收站。

运行 PowerShell 脚本。

# 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
}

它将硬删除 Azure AD 回收站中的所有用户。请参阅下面的 PowerShell 输出结果示例。

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.

你已成功使用 MS Graph PowerShell 软删除和硬删除 Azure AD 用户。

阅读更多内容:使用 PowerShell 管理 Office 365 回收站 »

结论

您了解了如何使用 Microsoft Graph PowerShell 删除 Azure AD 用户。使用Remove-MgUser cmdlet 将单个或多个Azure AD 用户帐户删除到回收站。假设要从回收站永久删除 Azure AD 用户,请使用Remove-MgDirectoryDeletedItem cmdlet。

您喜欢这篇文章吗?您可能还喜欢使用 PowerShell 强制删除 Microsoft 365 邮箱。不要忘记关注我们并分享这篇文章。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯