Azure ad – Powershell – remove user from group a if they are a member of group b

Azure ad – Powershell – remove user from group a if they are a member of group b

The below is the snippet.

If you are doing it for a single User :

 $user_upn = <USER UPN>
 $users= Get-AzureADGroupMember -ObjectId <GROUP B ID> -All $true

 #Finds for a specific user and if it exists, goes ahead and remove the specific user from the Group A
 $users |?{$_.UserPrincipalName -eq $user_upn} | %{Remove-AzureADGroupMember -ObjectId <GROUP A ID> -MemberId $_.objectid}

Explanation

Gets all the member of Group B and stores it in the variable $users.
Checks(Filters) whether the required member is present in the $users variable, if Yes, goes ahead and removes from the Group A.

If you are looking to do it for the list of UPNs from a File. You could refer to the below snippet.

 #Getting the list of UPNS of the users for whom the process specified needs to be carried out
 $user_upns = Get-Content C:ListUPN.txt
 
 #Iterates through each UPN
 foreach( $user_upn in $user_upns)
 {
 
 Write-Host Working on the $user_upn -ForegroundColor Green
 
 #Gets all user from the GROUP B
 $users= Get-AzureADGroupMember -ObjectId <GROUP B ID> -All $true
 
 #Finds for a specific user and if it exists, goes ahead and remove the specific user from the Group A
 $users |?{$_.UserPrincipalName -eq $user_upn} | %{Remove-AzureADGroupMember -ObjectId <GROUP A ID> -MemberId $_.objectid}

 }

This was Answered for me on another forum https://www.reddit.com/r/AZURE/comments/k910l4/azure_ad_powershell_help_user_group_memberships/

Kudos to TheStig1293 on reddit

#Store the groups in a variable
$GroupA = Get-AzureADGroupMember -ObjectId 746e5b45-9368-434c-bab1-5d5b7baea075

$GroupB = Get-AzureADGroupMember -ObjectId 90e136ce-f573-4b4f-9990-21a314963de2

#Using Compare-object to compare the members of the groups and then using Where-object to select the ones that are in both Groups. This is stored in a variable called Dif 
$diff = Compare-Object -ReferenceObject $GroupB.ObjectID -DifferenceObject $GroupA.ObjectID -IncludeEqual | Where-Object {$_.SideIndicator -eq ==}

#Using foreach to go through each user in diff and then removing them. We are referencing the InputObject property as the Object ID because if you look at the output of Compare-object, that is the anchor for the comparison. 

foreach($user in $diff){
    #I Included this so you can verify manually they are the users you would like to remove prior to removing. 
    #Get-AzureADUser -ObjectId $user.InputObject 
    Remove-AzureADGroupMember -ObjectID 746e5b45-9368-434c-bab1-5d5b7baea075 -MemberID ($User).InputObject
}

Azure ad – Powershell – remove user from group a if they are a member of group b

Leave a Reply

Your email address will not be published.