在 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。不要忘记关注我们并分享这篇文章。
