Still new to PowerShell and trying to use it more often to automate many tasks. I’m currently stuck trying to create a script that add all users that match certain department attribute to a group and remove those not in the specific departments. The adding part works fine but i haven’t been able to get the removal section to work. I need to use multiple -or statements and it just ends up removing all the users. Ultimately i would like to pull the list of departments that need access from a csv file and remove users not in the departments on the csv file but have been having to much trouble with that script. Any assistance would be great.
Here is what i have so far. I don’t get any errors but it ends up just removing all users so i think line 12 has issues. Just not sure what. And i realize my code is sloppy and there is probably a much better way to do this but i’m still a beginner and using what i can to make it work.
#Import the AD module import-module ActiveDirectory #Set your search OU and Group Variables $OU="OU=TestOU,DC=contoso,DC=com" $Group="CN=TestGroup,OU=TestGroupsDC=contoso,DC=com" #Adds any Authorized employee to the Group that currently is not a member of it Get-ADUser -LDAPFilter "(&(|(department=167*)(department=204*)(department=205*)(department=212*)(department=216*)(department=226*)(department=227*)(department=*30*)(department=231*)(department=232*)(department=236*)(department=*40*)(department=241*)(department=242*)(department=244*)(department=*46*)(department=*54*)(department=*57*)(department=274*)(department=276*)(department=280*)(department=404*)(department=405*)(department=431*)(department=232*)(department=436*)(department=441*)(department=444*)(department=427*)(department=427*)(department=442*))(useraccountcontrol=512)(!memberOf=$Group))" –SearchBase $OU –SearchScope Subtree | ForEach-Object {Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $Group} $membersToRemove = Get-ADGroupMember $Group | Get-ADUser -Properties * | ? { $_.department -notlike "167*" -or $_.department -notlike "204*"} Remove-ADGroupMember $Group $membersToRemove –Confirm:$false