Can add but not remove from Azure AD

61 Views Asked by At

I am able to add users to an Azure AD Security group from a csv, but am having trouble removing them from the Azure AD group (if they're in it) if they ARE NOT in the CSV. This part works just fine.

#Connect to Azure AD 
Connect-AzureAD

 #Import the list and save it to a variable
$list = Import-Csv "H:\BPT_Users_Reports\SCJ_BPT_Users_03-07-2024_test.csv"
#Insert the display name of the group here
$group = "BPT User Load Test"

#Retrieve the group name for use later in the script
$GroupObjectID = Get-AzureADGroup -SearchString $group | Select -Property ObjectID

#roll through the list to look up each user and add to the group. 
foreach ($y in $list){
    $y2 = Get-AzureADUser -ObjectId $y.userPrincipalName | Select -Property ObjectID
    $members = Get-AzureADGroupMember -ObjectId $GroupObjectID.ObjectID -All $true

    if ($y2.ObjectID -in $members.ObjectID) {
    Write-Host $y.userPrincipalName'is already in the Group' -ForegroundColor Blue
    }else{
        Add-AzureADGroupMember -ObjectId $GroupObjectID.ObjectID -RefObjectId $y2.ObjectId -              InformationAction SilentlyContinue
    Write-Host $y.userPrincipalName'has been added to the Group' -ForegroundColor Green
    }

}

#Disconnect Azure AD
Disconnect-AzureAD

Basically, if they no longer meet the requirements to be in the CSV file, I want them removed from the Azure AD group. If tried adding additional FOR EACH statements that if NOT in the CSV then remove from Azure AD group. It goes through the motions, but doesn't remove them.

ForEach ($y in $list)
{
       {        
        $UserObj = Get-AzureADUser -ObjectId $y.UPN
        Where-Object {$Group -notcontains $y.UPN}
        Remove-AzureADGroupMember -ObjectID $Group.ObjectID -RfObjectId.ObjectID 
   }
}   
1

There are 1 best solutions below

4
Jahnavi On BEST ANSWER

Can add but not remove from Azure AD:

Adding member to a group code looks good to me. I modified a little bit of your script to the removal part.

foreach ($mem in $members) {
    $existing = $mem.UserPrincipalName
    if ($list.UserPrincipalName -notcontains $existing) {
        Write-Host "removing $existing member from the group"
        Remove-AzureADGroupMember -ObjectId $GroupObjectID.ObjectID -MemberId $mem.ObjectId
    }
}

enter image description here