使用 Microsoft Entra PowerShell 管理用户

用户是 Microsoft Entra ID 中的 Microsoft Entra 工作或学校用户帐户或个人 Microsoft 帐户的表示形式。 Microsoft Entra PowerShell 中的用户资源是用户的表示形式,包括与用户相关的关系和资源。

用户资源提供了一种直接的方法,可用于访问和操作用户资源,而无需执行额外的调用、查找特定的身份验证信息,并直接针对其他 Microsoft Entra PowerShell 对象发出查询。

先决条件

若要使用 Microsoft Entra PowerShell 管理用户,需要:

你可以代表用户,或以具有自身标识的应用程序身份,访问用户信息并管理其数据。

载入用户

若要载入用户,请在Microsoft Entra ID中创建新的用户帐户。 此过程涉及设置用户的个人资料,包括其显示名称、电子邮件地址和密码。

创建用户

此示例创建一个新用户。

Connect-Entra -Scopes 'User.ReadWrite.All'
$passwordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$passwordProfile.Password = '<Strong-Password>'
$userParams = @{
    DisplayName = 'New User'
    PasswordProfile = $passwordProfile
    UserPrincipalName = 'NewUser@contoso.com'
    AccountEnabled = $true
    MailNickName = 'NewUser'
}
New-EntraUser @userParams

输出显示新创建用户的详细信息。

DisplayName    Id                                     Mail    UserPrincipalName
-----------    --                                     ----    -----------------
New User       aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb           NewUser@contoso.com

批量创建用户

若要批量创建多个用户,可以使用 CSV 文件。 CSV 文件应包含必要的用户属性,例如 DisplayNameUserPrincipalNamePasswordProfile

# Connect to Microsoft Entra PowerShell
Connect-Entra -Scopes 'User.ReadWrite.All'

# Create a new Password Profile for the new users. We'll be using the same password for all new users in this example
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = '<Your-Password>'

# Import the csv file. You will need to specify the path and file name of the CSV file in this cmdlet
$NewUsers = import-csv -Path '<path-to-your-csv-file>'

# Loop through all new users in the file to create them in Microsoft Entra ID
ForEach ($user in $NewUsers) {
    # Create a new user in Microsoft Entra ID
    New-EntraUser -UserPrincipalName $user.'EmailAddress' -DisplayName $user.'DisplayName' -GivenName $user.'FirstName' -Surname $user.'LastName' -Department $user.'Department' -MailNickname $user.'MailNickname' -AccountEnabled $true -PasswordProfile $passwordProfile
    }
名字 姓氏 DisplayName 电子邮件地址 部门 邮件昵称
Adele Vance 阿黛尔·万斯 adelev@contoso.com Marketing adelev

输出显示新创建的用户的详细信息。

DisplayName Id                                   Mail UserPrincipalName
----------- --                                   ---- -----------------
Adele Vance aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb      adelev@contoso.com

更新用户的密码

  1. 若要由管理员更新用户的密码,请使用以下命令:

    Connect-Entra -Scopes 'Directory.AccessAsUser.All'
    $newPassword = '<strong-password>'
    $securePassword = ConvertTo-SecureString $newPassword -AsPlainText -Force
    Set-EntraUserPasswordProfile -UserId 'SawyerM@contoso.com' -Password $securePassword
    
  2. 若要更新已登录用户(自助服务)的密码,请使用以下命令:

    Connect-Entra -Scopes 'Directory.AccessAsUser.All'
    $currentPassword = ConvertTo-SecureString '<strong-password>' -AsPlainText -Force
    $newPassword = ConvertTo-SecureString '<strong-password>' -AsPlainText -Force
    Set-EntraSignedInUserPassword -CurrentPassword $currentPassword -NewPassword $newPassword
    

    此命令允许用户在没有管理员权限的情况下更改自己的密码。

上传或检索用户的照片

  1. 为用户上传照片。

    Connect-Entra -Scopes 'User.ReadWrite.All'
    Set-EntraUserThumbnailPhoto -UserId 'SawyerM@contoso.com' -FilePath 'D:\UserThumbnailPhoto.jpg'
    

    本示例将使用 UserId 参数指定的用户的缩略图照片设置为使用 FilePath 参数指定的图像。

  2. 检索用户的照片。

    Connect-Entra -Scopes 'ProfilePhoto.Read.All'
    Get-EntraUserThumbnailPhoto -UserId 'SawyerM@contoso.com'
    

    此示例演示如何检索通过参数值 UserId 指定的用户的缩略图照片。

向贵组织中的用户授予管理员角色

授予组织中的用户管理角色,允许他们执行特定任务和管理资源。 可以将用户分配到组管理员、用户管理员或其他自定义角色等角色。

若要了解如何使用 Microsoft Entra PowerShell 向用户分配角色,请参阅向用户分配角色

搜索用户

可以使用各种属性(例如displayNamemailNicknameuserPrincipalNamedepartmentjobTitle)搜索组织中的用户。 以下示例演示如何通过 userPrincipalName 搜索用户

Connect-Entra -Scopes 'User.Read.All'
Get-EntraUser -Filter "userPrincipalName eq 'SawyerM@contoso.com'"

输出显示基于 userPrincipalName 搜索的用户详细信息。

DisplayName      Id                                   Mail                 UserPrincipalName     
-----------      --                                   ----                 -----------------     
Sawyer Miller   aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb SawyerM@contoso.com  SawyerM@contoso.com   

按特定条件审核用户

可以按某些条件(例如登录活动)和组成员身份来审核用户。 此功能可帮助你跟踪用户活动并管理他们对资源的访问。

检索用户的登录活动

以下示例演示如何检索特定用户的登录活动。

Connect-Entra -Scopes 'User.Read.All','AuditLog.Read.All'
Get-EntraUser -UserId 'SawyerM@contoso.com' -Property 'SignInActivity' | 
  Select-Object -Property Id, DisplayName, UserPrincipalName -ExpandProperty 'SignInActivity'

输出显示用户的登录活动。

lastNonInteractiveSignInRequestId : bbbbbbbb-1111-2222-3333-aaaaaaaaaaaa
lastSignInRequestId               : cccccccc-2222-3333-4444-dddddddddddd
lastSuccessfulSignInDateTime      : 9/9/2024 1:12:13 PM
lastNonInteractiveSignInDateTime  : 9/9/2024 1:12:13 PM
lastSuccessfulSignInRequestId     : bbbbbbbb-1111-2222-3333-aaaaaaaaaaaa
lastSignInDateTime                : 9/7/2024 9:15:41 AM
id                                : aaaaaaaa-bbbb-cccc-1111-222222222222
displayName                       : Sawyer Miller
userPrincipalName                 : SawyerM@contoso.com

下载所有用户的登录活动

以下示例检索所有许可的用户帐户及其上次成功登录活动。 它将数据导出到 CSV 文件以供进一步分析。

# Connect to Microsoft Entra PowerShell  

Connect-Entra -Scopes 'User.Read.All','AuditLog.Read.All','Directory.Read.All'

try {
     Get-EntraUser -All -Property Id, UserPrincipalName, DisplayName, SignInActivity -ErrorAction Stop |
         Select-Object `
             Id, `
             UserPrincipalName, `
             DisplayName, `
             @{ Name = 'LastSignInDateTime';           Expression = { $_.SignInActivity.LastSignInDateTime } }, `
             @{ Name = 'LastSuccessfulSignInDateTime'; Expression = { $_.SignInActivity.LastSuccessfulSignInDateTime } } |
         Export-Csv -Path 'C:\temp\lastSignIns.csv' -NoTypeInformation -Encoding UTF8 -ErrorAction Stop

     Write-Host "Sign-in activity exported successfully to lastSignIns.csv"
 }
 catch {
     Write-Error "Failed to retrieve or export data: $_"
 }

此示例检索组织中所有用户的最后一次登录和上次成功登录日期。 然后,数据将导出到目录中命名 lastSignIns.csvC:\temp CSV 文件。

列出用户的组成员身份

以下示例列出用户所属的组。

Connect-Entra -Scopes 'User.Read'
Get-EntraUserMembership -UserId 'SawyerM@contoso.com' |
 Select-Object Id, displayName, createdDateTime, '@odata.type' |
 Format-Table -AutoSize

输出显示用户的成员身份。

Id                                   displayName                         createdDateTime      @odata.type
--                                   -----------                         ---------------      -----------
00aa00aa-bb11-cc22-dd33-44ee44ee44ee Contoso                             2024-10-06T08:49:16Z #microsoft.graph.group
22cc22cc-dd33-ee44-ff55-66aa66aa66aa Contoso marketing                   2024-10-07T01:17:28Z #microsoft.graph.group
55ff55ff-aa66-bb77-cc88-99dd99dd99dd Pacific Admin Unit                                       #microsoft.graph.administrativeUnit

使用以下命令列出用户所属的实体:

获取用户的经理、直接下属并为用户分配经理

  1. 获取用户的经理。

    Connect-Entra -Scopes 'User.Read.All'
    Get-EntraUserManager -UserId 'SawyerM@contoso.com' |
        Select-Object Id, displayName, userPrincipalName, createdDateTime, accountEnabled, userType |
        Format-Table -AutoSize
    

    输出内容显示用户的直属经理。

    id                                    displayName     userPrincipalName                    createdDateTime           accountEnabled  userType
    --                                    -----------     -----------------                    ---------------           --------------  --------
    11bb11bb-cc22-dd33-ee44-55ff55ff55ff  Patti Fernandez PattiF@Contoso.com                 10/7/2024 12:32:01 AM      True           Member
    
  2. 列出向特定用户报告的用户。

    Connect-Entra -Scopes 'User.Read','User.Read.All'
    Get-EntraUserDirectReport -UserId 'SawyerM@contoso.com' |
        Select-Object Id, displayName, userPrincipalName, createdDateTime, accountEnabled, userType |
        Format-Table -AutoSize
    

    输出显示用户的直接报告。

    id                                    displayName     userPrincipalName           createdDateTime       accountEnabled  userType
    --                                    -----------     -----------------           ---------------       --------------  --------
    bbbbbbbb-1111-2222-3333-cccccccccccc  Christie Cline  ChristieC@Contoso.com       10/7/2024 12:32:25 AM  True           Member
    aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb  Isaiah Langer   IsaiahL@Contoso.com         10/7/2024 12:33:16 AM  True           Member
    
  3. 为用户指定经理。

    Connect-Entra -Scopes 'User.ReadWrite.All'
    Set-EntraUserManager -UserId 'SawyerM@contoso.com' -ManagerId 'AdeleV@contoso.com'
    
    • -UserId - 指定 Microsoft Entra ID 中某个用户的 ID(以 UserPrincipalName 或 User ObjectId 的形式)。
    • -ManagerId - 指定要分配为经理的 Microsoft Entra ID 对象的 ID(作为 UserPrincipalName 或 User ObjectId)。

列出没有经理的用户

此示例列出没有直属上级的用户,有助于识别孤立账户、服务账户或配置错误的用户资料,以便进行清理。

Connect-Entra -Scopes 'User.Read.All'
$allUsers = Get-EntraUser -All
$usersWithoutManagers = foreach ($user in $allUsers) {
    $manager = Get-EntraUserManager -UserId $user.Id -ErrorAction SilentlyContinue
    if (-not $manager) {
        [PSCustomObject]@{
            Id                = $user.Id
            DisplayName       = $user.DisplayName
            UserPrincipalName = $user.UserPrincipalName
            UserType          = $user.userType
            AccountEnabled    = $user.accountEnabled
            CreatedDateTime   = $user.createdDateTime
        }
    }
}
$usersWithoutManagers | Format-Table Id, DisplayName, UserPrincipalName, CreatedDateTime, UserType, AccountEnabled  -AutoSize

输出列出了没有经理的用户。

Id                                   DisplayName         UserPrincipalName                           CreatedDateTime           UserType   AccountEnabled
--                                   -----------         -----------------                           ---------------           --------   --------------
cccccccc-2222-3333-4444-dddddddddddd New User           NewUser@tenant.com                         10/7/2024 2:24:26 PM      Member     True
bbbbbbbb-1111-2222-3333-cccccccccccc Sawyer Miller     SawyerM@contoso.com                        10/7/2024 12:33:36 AM     Member     True

列出禁用的用户

以下示例生成已禁用帐户的列表。

Connect-Entra -Scopes 'User.ReadWrite.All'
Get-EntraUser -Filter "accountEnabled eq false" | Select-Object DisplayName, Id, Mail, UserPrincipalName

输出列出了禁用的用户。

DisplayName    Id                                   Mail userPrincipalName
-----------    --                                   ---- -----------------
Sawyer Miller  hhhhhhhh-7777-8888-9999-iiiiiiiiiiii      SawyerM@contoso.com
Kez Michael    eeeeeeee-4444-5555-6666-ffffffffffff      KezM@contoso.com