-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathCopy_groupmembership_new_user.ps1
39 lines (33 loc) · 1.43 KB
/
Copy_groupmembership_new_user.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#Use Windows PowerShell ISE or Azure Cloud Shell
#Install AzureAD (The module has been deprecated, but is still working at the moment)
Install-Module -Name AzureAD -AllowClobber -Verbose -Force
#Parameters
$SourceAccount = "[email protected]"
$TargetAccount = "[email protected]"
#Connect to Azure AD
Connect-AzureAD
#Get the source and target users
$SourceUser = Get-AzureADUser -Filter "UserPrincipalName eq '$SourceAccount'"
$TargetUser = Get-AzureADUser -Filter "UserPrincipalName eq '$TargetAccount'"
#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" }
#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 $TargetAccount)
{
#Add target user to the source user's group
Add-AzureADGroupMember -ObjectId $Membership.ObjectId -RefObjectId $TargetUser.ObjectId
Write-host "User added to the group:" $Membership.DisplayName
}
}
}
Else
{
Write-host "Invalid source or target user!" -f Yellow
}