使用 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
    }
FirstName 姓氏 DisplayName 電子郵件地址 部門 郵件暱稱
李莉華 Vance 阿黛爾·萬斯 adelev@contoso.com Marketing 阿德列夫

輸出會顯示新建立使用者的詳細資訊。

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 將角色指派給使用者,請參閱「指派角色給使用者」。

搜尋使用者

你可以使用各種屬性搜尋組織中的使用者,例如displayName、、 mailNicknameuserPrincipalNamedepartmentjobTitle、 。 以下範例說明如何依 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