I am looking for a way to copy all the distribution lists from one of our users to a new user who is in a similar role.
All the scripts i've found so far are for on-prem AD.
I tried the below script and I got the bottom result when attempting to copy groups that are managed by Exchange Online.
#Parameters
$SourceUserAccount = "user1@test"
$TargetUserAccount = "user2@test"
#Connect to Azure AD
Connect-AzureAD
#Get the Source and Target users
$SourceUser = Get-AzureADUser -Filter "UserPrincipalName eq '$SourceUserAccount'"
$TargetUser = Get-AzureADUser -Filter "UserPrincipalName eq '$TargetUserAccount'"
#Check if source and Target users are valid
If($SourceUser -ne $Null -and $TargetUser -ne $Null)
{
#Get All memberships of the Source user
$SourceMemberships = Get-AzureADUserMembership -ObjectId $SourceUser.ObjectId | Where-object { $_.ObjectType -eq "Group" }
#Get-AzureADUserOwnedObject -ObjectId $SourceUser.ObjectId
#Loop through Each Group
ForEach($Membership in $SourceMemberships)
{
#Check if the user is not part of the group
$GroupMembers = (Get-AzureADGroupMember -ObjectId $Membership.Objectid).UserPrincipalName
If ($GroupMembers -notcontains $TargetUserAccount)
{
#Add Target user to the Source User's group
Add-AzureADGroupMember -ObjectId $Membership.ObjectId -RefObjectId $TargetUser.ObjectId
Write-host "Added user to Group:" $Membership.DisplayName
}
}
}
Else
{
Write-host "Source or Target user is invalid!" -f Yellow
}
This is the error:
Error occurred while executing AddGroupMember
Code: Request_BadRequest
Message: Cannot Update a mail-enabled security groups and or distribution list.
RequestId: 887f93ae-590a-4c8a-b4ed-98d82357ef6a
DateTimeStamp: Thu, 23 Feb 2023 04:25:07 GMT
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed
At line:20 char:1
+ Add-AzureADGroupMember -ObjectId $group.ObjectId -RefObjectId $user2O ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-AzureADGroupMember], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.
PowerShell.AddGroupMember