I am trying to get a list of workstations that are not in eiter of two specific security groups. I want to see workstation that are not in the "MDM Newyork" group or not in the "MDM California". I scripted it as follows:
$filter1 = "(!(memberOf=CN=MDM Newyork,OU=Cloud Apps,OU=Groups,DC=companyX,DC=com))"
$filter2 = "(!(memberOf=CN=MDM California,OU=Cloud Apps,OU=Groups,DC=companyX,DC=com))"
Get-ADComputer -LDAPFilter ($filter1 -or $filter2) -SearchBase "OU=Prod Workstations,DC=companyX,DC=com" -Properties * | select name, @{n="OU"; e={$_.DistinguishedName -replace '^.*?,(?=[A-Z]{2}=)'}} | sort OU
I know there are many workstations that are not either of those groups but this script returns no results. If I run the script with out the "-or" with just $filter1 it returns results correctly for any workstation not in the MDM Newyork group. If i run it ith out the "-or" with just $filter2 it returns results correctly for any workstation not in the MDM California group. It just does not return reseults when I try to combine the two filters with and or statement.
Any idea where my logic is flawed? Its not a syntax error as it runs with out and error, just does not return anything matching my conditions.
You have already figured it out but ($filter1 -or $filter2)
is an invalid filter in LDAP Syntax. The OR Operator in LDAP is |
, have a look at Active Directory: LDAP Syntax Filters to learn more.
There is another logical issue:
not in either of two specific security groups
Means that you want AND (&
) instead of OR (|
), so the actual filter could be:
$filter1 = '(!memberOf=CN=MDM Newyork,OU=Cloud Apps,OU=Groups,DC=companyX,DC=com)'
$filter2 = '(!memberOf=CN=MDM California,OU=Cloud Apps,OU=Groups,DC=companyX,DC=com)'
$filterFinal = "(&${filter1}${filter2})"
# Also valid ways to create the filter:
#
# $filterFinal = '(&' + $filter1 + $filter2 + ')'
# $filterFinal = '(&{0}{1})' -f $filter1, $filter2
Get-ADComputer -LDAPFilter $filterFinal ....