Hi, i’m new to using Powershell and am trying to create a script to automatically add all users with a specific attribute in AD to a Group and remove any from that group that do not have this attribute. I have just one section of a line that is not working and keeps giving errors. Any assistance would be great
Here is what i have:
#Import the AD module
ipmort-module ActiveDirectory
#Set your search OU and Group Variables
$OU=“OU=,DC=,DC=com”
$Group=“CN=GroupNameHere,OU=,DC=,DC=com”
#Pull current list of Group Members and remove anyone not a Regular Employee - This part works fine
Get-ADGroupMember –Identity $Group | Where-Object {$.extensionAttribute2 –NotMatch “Regular”} | ForEach-Object {Remove-ADPrincipalGroupMembership –Identity $ –MemberOf $Group –Confirm:$false}
#Adds any Regular employee to the Group that currently is not a member of it - This is where my issue is. The LDAPfilter to check if user already in a group is not working. I want to find any user with the attribute listed set to 'Regular" and add them to this group if they are not already in it.
Get-ADUser -Filter {extensionAttribute2 -like “Regular”} –SearchBase $OU –SearchScope Subtree –LDAPFilter “(!memberOf=$Group)” | ForEach-Object {Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $Group}