Earlier today, I got help adding members to a group if they are not a member of it.
$group = 'CN=Group1,OU=SomeOU,DC=domain,DC=local'
Get-ADUser -LDAPFilter "(!memberof=$group)" -SearchBase "DC=domain,DC=local" |
Add-ADPrincipalGroupMembership -MemberOf $group
Now I want to reverse that and remove members from the group if they are not in the specific OU I used as the -SearchBase. Does this look correct?
$group = 'CN=Group1,OU=SomeOU,DC=domain,DC=local'
Get-ADGroupMember -Identity $group |
Where-Object { $_.DistinguishedName -notlike "*DC=domain,DC=local" } |
Remove-ADPrincipalGroupMembership -MemberOf $group
CodePudding user response:
To reverse the order would mean to query the Group's Member
attribute and filter those DistinguishedNames not containing the base DistinguishedName. -notlike
can act as a filter on collection of values hence:
$group = 'CN=Group1,OU=SomeOU,DC=domain,DC=local'
$base = 'DC=domain,DC=local'
(Get-ADGroup $group -Properties member).member -notlike "*$base" |
Remove-ADPrincipalGroupMembership -MemberOf $group