AZURE AD Groups Removal Failing when an user is disabled (or) teminated

When have developed the PowerShell script for Azure AD groups removal when an user is terminated or disabled. some of the terminated user are removing from your PowerShell automated script and many of terminated user were not able to remove these groups.
Note: “we are trying to remove only standard groups which are assigned once and we are skipping the dynamic groups”.
If you have any PowerShell scripts please provide and let me know your valuable suggestion’s to fix this issue.

Hey @mrahulbb , how are you?

Try to check for the group attributes there’s a specific attribute to differ from dynamic to security groups, that way you can only remove what you want.

Like that

# Define user and group names (replace with your actual values)
$userName = "JohnDoe"
$groupName = "SalesTeam"

# Load Active Directory module
Import-Module ActiveDirectory

# Get user object
$user = Get-ADUser -Identity $userName

# Get user's group memberships
$groups = Get-ADPrincipalGroupMembership -Identity $user

# Function to check if group is security group
function IsSecurityGroup($group) {
  # Check for GroupCategory "Security"
  $group.GroupCategory -eq "Security"
}

# Loop through groups and remove user only from security groups
foreach ($group in $groups) {
  if (IsSecurityGroup($group)) {
    # Remove user from the security group
    Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $group
    Write-Host "Removed user '$userName' from security group '$($group.Name)'"
  } else {
    Write-Host "User '$userName' is not a member of security group '$($group.Name)'"
  }
}

Best

What is the error that you are getting while removing access ?

It is not showing any error but it is removing few users

Hello @mrahulbb,

As you say “we are trying to remove only standard groups which are assigned once and we are skipping the dynamic groups”.

I think for those users it’s may be dynamics groups.

Best regards.

No in Azure portal we are able to see assigned groups as well

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.