在 Microsoft Entra ID 中將組成員資格從一個用戶複製到另一個用戶
您需要為用戶提供與其他用戶相同的組成員身份。您可以通過將每個組單獨添加到用戶來手動執行此操作。但這需要時間。更好的方法是使用 PowerShell 自動化該過程。在本文中,您將了解如何在 Microsoft Entra ID 中將組成員身份從一個用戶複製到另一個用戶。
複製組成員資格 PowerShell 腳本
Copy-GroupMembership.ps1 PowerShell 腳本會將指定用戶(源)的組成員身份複製到 Microsoft Entra ID 中的另一個用戶(目標)。
筆記:該腳本無法複製啟用郵件的安全組或通訊組列表,因為這些需要使用 Exchange Online PowerShell 進行管理。此外,如果組是從本地 Active Directory 同步的,您只能從那裡管理它,而不能在 Microsoft Entra ID 中管理它。
這是用戶的組成員身份的示例[電子郵件受保護]。
步驟 1. 安裝 Microsoft Graph PowerShell
以管理員身份運行 Windows PowerShell 並安裝 Microsoft Graph PowerShell。
Install-Module Microsoft.Graph -Force
重要的:在運行 cmdlet 或腳本之前,請務必更新到最新的 Microsoft Graph PowerShell 模塊版本,以防止出現錯誤和不正確的結果。
現在我們已經安裝了 Microsoft Graph PowerShell SDK 模塊,我們可以進入下一步。
步驟 2. 連接到 Microsoft Graph PowerShell
您需要使用正確的權限連接到 Microsoft Graph PowerShell。
Connect-MgGraph -Scopes "User.Read.All", "Group.Read.All", "GroupMember.ReadWrite.All" -NoWelcome
步驟 3. 下載 Copy-Membership PowerShell 腳本
上創建兩個文件夾(中:)駕駛:
- 腳本
- 溫度
下載 Copy-GroupMembership.ps1 PowerShell 腳本並將其放置在C:腳本文件夾。該腳本會將指定用戶的所有組成員身份複製到 Microsoft Entra ID 中的另一個用戶。
確保文件未被阻止,以防止運行腳本時出現錯誤。請閱讀文章運行 PowerShell 腳本時出現未數字簽名錯誤來了解更多信息。
另一種選擇是將以下代碼複製並粘貼到記事本中。給它起個名字複製 GroupMemberships.ps1並將其放置在C:腳本文件夾。
<#
.SYNOPSIS
Copy-GroupMemberships.ps1
.DESCRIPTION
Copy all group memberships of a specified user to another user in Microsoft Entra ID.
.LINK
www.alitajran.com/copy-group-membership-from-one-user-to-another-in-microsoft-entra-id/
.NOTES
Written by: ALI TAJRAN
Website: www.alitajran.com
LinkedIn: linkedin.com/in/alitajran
X: x.com/alitajran
.CHANGELOG
V1.00, 05/25/2025 - Initial version
#>
# Define parameters for the script
param (
[Parameter(Mandatory = $true, HelpMessage = "Enter the User ID (e.g., email or object ID) of the source Entra ID user")]
[string]$UserId,
[Parameter(HelpMessage = "Specify the path for the CSV output file")]
[string]$CsvFilePath,
[Parameter(HelpMessage = "Enable to display results in Out-GridView")]
[switch]$OutGridView,
[Parameter(HelpMessage = "Enter the User ID (e.g., email or object ID) of the target user to copy memberships to")]
[string]$TargetUserId
)
# Connect to Microsoft Graph with required scopes
Connect-MgGraph -Scopes "User.Read.All", "Group.Read.All", "GroupMember.ReadWrite.All" -NoWelcome
# Initialize a list to store report data
$Report = [System.Collections.Generic.List[Object]]::new()
try {
# If TargetUserId is provided, verify target user exists
if ($TargetUserId) {
$TargetUser = Get-MgUser -UserId $TargetUserId -ErrorAction Stop
}
# Fetch the source user's group memberships
$EntraGroupMembers = Get-MgUserMemberOf -UserId $UserId -All -ErrorAction Stop
# Check if the source user is a member of any groups
if (-not $EntraGroupMembers) {
Write-Host "No group memberships found for user: $UserId" -ForegroundColor Cyan
return
}
# Process each group membership
foreach ($EntraGroup in $EntraGroupMembers) {
# Extract group details from AdditionalProperties
$AdditionalProperties = $EntraGroup.AdditionalProperties
# Determine group type
$GroupType = if ($AdditionalProperties.groupTypes -contains "Unified" -and $AdditionalProperties.securityEnabled) {
"Microsoft 365 (security-enabled)"
}
elseif ($AdditionalProperties.groupTypes -contains "Unified" -and -not $AdditionalProperties.securityEnabled) {
"Microsoft 365"
}
elseif (-not ($AdditionalProperties.groupTypes -contains "Unified") -and $AdditionalProperties.securityEnabled -and $AdditionalProperties.mailEnabled) {
"Mail-enabled security"
}
elseif (-not ($AdditionalProperties.groupTypes -contains "Unified") -and $AdditionalProperties.securityEnabled) {
"Security"
}
elseif (-not ($AdditionalProperties.groupTypes -contains "Unified") -and $AdditionalProperties.mailEnabled) {
"Distribution"
}
else {
"N/A"
}
# Create a custom object for the group details
$GroupDetails = [PSCustomObject]@{
Id = $EntraGroup.Id
DisplayName = if ($AdditionalProperties.displayName) { $AdditionalProperties.displayName } else { "N/A" }
Email = if ($AdditionalProperties.mail) { $AdditionalProperties.mail } else { "N/A" }
SecurityEnabled = if ($AdditionalProperties.securityEnabled) { $AdditionalProperties.securityEnabled } else { "N/A" }
MailEnabled = if ($AdditionalProperties.mailEnabled) { $AdditionalProperties.mailEnabled } else { "N/A" }
GroupType = $GroupType
Source = if ($AdditionalProperties.onPremisesSyncEnabled) { "On-Premises" } else { "Cloud" }
}
# Add the group details to the report list
$Report.Add($GroupDetails)
}
# Output to console only if TargetUserId is not provided
if (-not $TargetUserId) {
$Report | Sort-Object DisplayName | Format-Table -AutoSize
}
# Output to Out-GridView if specified
if ($OutGridView) {
$Report | Sort-Object DisplayName | Out-GridView -Title "Group Memberships for $UserId"
}
# Export to CSV if CsvFilePath is provided
if ($CsvFilePath) {
$Report | Sort-Object DisplayName | Export-Csv -Path $CsvFilePath -NoTypeInformation -Force
Write-Host "Group memberships exported to $CsvFilePath" -ForegroundColor Cyan
}
# Copy memberships to target user if TargetUserId is provided
if ($TargetUserId) {
foreach ($Group in $Report) {
try {
# Check if the target user is already a member
$ExistingMember = Get-MgGroupMember -GroupId $Group.Id -All | Where-Object { $_.Id -eq $TargetUser.Id }
if (-not $ExistingMember) {
New-MgGroupMember -GroupId $Group.Id -DirectoryObjectId $TargetUser.Id -ErrorAction Stop
Write-Host "Added $TargetUserId to group: $($Group.DisplayName)" -ForegroundColor Green
}
else {
Write-Host "User $TargetUserId is already a member of group: $($Group.DisplayName)" -ForegroundColor Yellow
}
}
catch {
Write-Host "Failed to add $TargetUserId to group $($Group.DisplayName): $($_.Exception.Message)" -ForegroundColor Red
}
}
}
}
catch {
# Handle errors (e.g., invalid UserId, insufficient permissions, or Graph API issues)
Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
}
步驟 4. 運行 Copy-GroupMembership PowerShell 腳本
運行以下命令以獲取用戶的組成員身份。
C:scripts.Copy-GroupMemberships.ps1 -UserId "[email protected]"
運行以下命令以獲取用戶的組成員身份,並在單獨窗口的交互式表中顯示輸出。
C:scripts.Copy-GroupMemberships.ps1 -UserId "[email protected]" -OutGridView
運行以下命令以獲取用戶的組成員身份,在單獨窗口的交互式表中顯示輸出,並將結果導出到 CSV 文件。
C:scripts.Copy-GroupMemberships.ps1 -UserId "[email protected]" -OutGridView -CsvFilePath "C:tempAmanda_GroupMemberships.csv"
輸出始終出現在 PowerShell 中。
Id DisplayName Email SecurityEnabled MailEnabled GroupType Source
-- ----------- ----- --------------- ----------- --------- ------
d62bbb93-90d6-4560-94f5-7536cb1d5ac5 All Company [email protected] N/A True Microsoft 365 Cloud
c36abb7f-30e6-4cf5-9c12-12a4b8184d96 DG001 [email protected] N/A True Distribution Cloud
068346f3-3b9a-44b8-81ff-db5167644d74 Group1_WR N/A True N/A Security Cloud
496c0a4a-91a0-4c5c-bbd3-b4bb30211e56 HR N/A True N/A Security Cloud
7def1c3e-ccbe-4458-ac41-8e9452460e9a Sales [email protected] N/A True Microsoft 365 Cloud
複製源用戶的組成員([電子郵件受保護])到目標用戶([電子郵件受保護])。
C:scripts.Copy-GroupMemberships.ps1 -UserId "[email protected]" -TargetUserId "[email protected]"
出現輸出。
Added [email protected] to group: Group1_WR
Added [email protected] to group: All Company
User [email protected] is already a member of group: Sales
Failed to add [email protected] to group DG001: [Request_BadRequest] : Cannot Update a mail-enabled security groups and or distribution list.
Added [email protected] to group: HR
驗證組成員身份是否已成功複製。
C:scripts.Copy-GroupMemberships.ps1 -UserId "[email protected]" -OutGridView -CsvFilePath "C:tempElisa_GroupMemberships.csv"
這就是目標用戶 Elisa Malor 的組成員身份。
就是這樣!
結論
您了解瞭如何在 Microsoft Entra ID 中將組成員資格從一個用戶複製到另一個用戶。使用 PowerShell 腳本獲取用戶的組成員身份(源)。然後,將其複製到另一個用戶(目標)。驗證組成員身份是否已成功添加到目標用戶。
您喜歡這篇文章嗎?您可能還喜歡如何在 PowerShell 中使用 Get-MgUser。不要忘記關注我們並分享這篇文章。
