Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Connect-MgGraph -Scopes "Group.ReadWrite.All", "User.Read.All"
- #Target Group ID
- $TargetGroupID = "GroupID"
- $TargetGroup = Get-MgGroup -GroupId $TargetGroupID
- #Extract groups from .yaml into a readable array
- $groups = Get-Content -Path "filepath.yaml" -Raw | ConvertFrom-Yaml
- #variable nulls
- $Yaml_Members_Source = $null
- $AAD_Members_Target = $null
- $fullGroup = $null
- $Yaml_Ids = $null
- $AAD_Ids = $null
- $Full_Details_Add = $null
- $Full_Details_Remove = $null
- #hashsets creation
- $Yaml_Members_Source = New-Object System.Collections.Generic.HashSet[string]
- $AAD_Members_Target = New-Object System.Collections.Generic.HashSet[string]
- #source hashset population
- foreach ($group in $groups) {
- $fullGroup = Get-MgGroup -Filter "displayName eq '$group'"
- [String[]]$Yaml_Ids = @(Get-MgGroupMember -GroupId $fullGroup.Id).Id
- $Yaml_Members_Source.UnionWith($Yaml_Ids)
- }
- #target hashset population
- [String[]]$AAD_Ids = @(Get-MgGroupMember -GroupId $TargetGroupID).Id
- $AAD_Members_Target.UnionWith($AAD_Ids)
- #Determine users to add and remove from Target
- $Users_To_Add = $Yaml_Members_Source.Where({$_ -notin $AAD_Members_Target})
- $Users_To_Remove = $AAD_Members_Target.Where({$_ -notin $Yaml_Members_Source})
- #Add users missing from Source to Target
- ForEach ($ADD_member in $Users_To_Add) {
- try {
- $Full_Details_Add = Get-MgUser -UserID $ADD_member -ErrorAction:SilentlyContinue
- }
- catch {
- Write-error "User ""$($Full_Details_Add.UserPrincipalName)"" was not found"
- }
- try {
- New-MgGroupMember -GroupId $TargetGroupID -DirectoryObjectId $ADD_member -ErrorAction:SilentlyContinue
- Write-Information "User ""$($Full_Details_Add.UserPrincipalName)"" added to ""$($TargetGroup.DisplayName)"""
- }
- catch {
- Write-Debug "User ""$($Full_Details_Add.UserPrincipalName)"" is already a member of ""$($TargetGroup.DisplayName)"""
- }
- }
- #Remove users that are in Target but not in the Source
- ForEach ($Remove_member in $Users_To_Remove) {
- try {
- $Full_Details_Remove = Get-MgUser -UserID $Remove_member -ErrorAction:SilentlyContinue
- }
- catch {
- Write-error "User ""$($Full_Details_Remove.UserPrincipalName)"" was not found"
- }
- Remove-MgGroupMemberByRef -GroupId $TargetGroupID -DirectoryObjectId $Remove_member
- Write-Information "User ""$($Full_Details_Remove.UserPrincipalName)"" removed from ""$($TargetGroup.DisplayName)"""
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement