I have the below code that looks for users that are not a member of a group. I would like to filter to not a member of group A as well as not a member of group B
# Set the name of the specific group that should trigger copying
$groupA = "GroupA"
$copyDN = (Get-ADGroup $groupA).DistinguishedName
# Set the name of the VPN users group that should trigger copying
$groupB = "GroupB"
$vpnDN = (Get-ADGroup $GroupB).DistinguishedName
$targetOU = "OU=Users,OU=Lab01,DC=dbss,DC=tech"
$usersToProcess = Get-ADUser -Filter ("-not memberof -RecursiveMatch '$groupA'") -SearchBase $targetOU -SearchScope OneLevel -Properties DisplayName,SamAccountName,Mobile,Pager
Is there a better way to use Get-ADUser to accomplish this?
I have no idea how to do it with the -Filter
syntax but with LDAP Syntax (-LDAPFilter
) this is how your query would look like:
# Set the name of the specific group that should trigger copying
$groupA = 'GroupA'
$copyDN = (Get-ADGroup $groupA).DistinguishedName
# Set the name of the VPN users group that should trigger copying
$groupB = 'GroupB'
$vpnDN = (Get-ADGroup $GroupB).DistinguishedName
$getADUserSplat = @{
# Not a memberof `$copyDN` AND Not a memberof `$vpnDN`
LDAPFilter = '(&(!memberof={0})(!memberof={1}))' -f $copyDN, $vpnDN
SearchBase = 'OU=Users,OU=Lab01,DC=dbss,DC=tech'
SearchScope = 'OneLevel'
Properties = 'DisplayName', 'SamAccountName', 'Mobile', 'Pager'
}
$usersToProcess = Get-ADUser @getADUserSplat
If you wanted to do a recursive lookup for any of those groups you would need to include LDAP_MATCHING_RULE_IN_CHAIN to your filter:
LDAPFilter = '(&(!memberof:1.2.840.113556.1.4.1941:={0})(!memberof:1.2.840.113556.1.4.1941:={1}))' -f $copyDN, $vpnDN