R Texas
R Texas

Reputation: 45

Modify Active Directory group membership with powershell if title of user account changes

I am attempting to use PowerShell to remove users from a security group if their user account "title" changes.

I want to get all members of the Development Team security group and if the members of this group have a title other than Developer, remove the user from the group.

This is just an example and would be used for role based group maintenance based on title. If a user's title changes, their group membership would change via this scheduled script.

This script removes all members of the group instead of just the members where the user's title does not equal Developer. How can I modify the script to only remove users with a title not equal to Developer?

Import-Module ActiveDirectory
$groupname = 'Development Team'
$members = Get-ADGroupMember -Identity $groupname

foreach($member in $members)
{
   if($member.title -notlike 'Developer')
   {
      Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname
   }
}

Based on the info from LisaJ below, this is what the new script looks like. Works!

Import-Module ActiveDirectory
$groupname = 'Development Team'
$members = Get-ADUser -LDAPFilter "(&(!(title=Developer))(memberOf=cn=Development Team,ou=Security Groups,dc=domain,dc=com))"

foreach($member in $members)
{
    Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname
}

Upvotes: 0

Views: 1674

Answers (1)

LisaJ
LisaJ

Reputation: 1706

Title is not an attribute returned with get-adgroupmember, so all $member.title values are not "Developer" because the value is always null. I would use an LDAP filter like

Get-ADUser -LDAPFilter "(&(!(title=Developer))(memberOf=cn=Development Group,ou=groups,dc=example,dc=com))"

To identify accounts which need to be removed from the group. This filter returns a set of users that are members of the Development Group group (you'll need the proper fully qualified DN for the group) but whose title is not "Developer". Use your foreach on those to remove-adgroupmember.

You can also provision users into the group when their title becomes developer using

Get-ADUser -LDAPFilter "(&(title=Developer)(!(memberOf=cn=Development Group,ou=groups,dc=example,dc=com)))"

To identify all accounts that are not a member of "Development Group" and have "Developer" as their title.

Upvotes: 1

Related Questions