I've built a filter to look for a number of AD fields and properties that works well until I try to add a section looking for 'enabled -eq $true.'
Here is the filter that works successfully:
$filter = "(&(msExchMailboxguid=*)" "(facilityID=12345)" "(|(jobCodeID=0001)" "(jobCodeID=0002)" "(jobCodeID=0003)(jobCodeID=0004)" "(jobCodeID=0005)" "(jobCodeID=0006)))"
Get-ADUser -SearchBase "dc=acme,dc=corp" -LDAPFilter $filter
This works, and produces the correct AD user objects (four total).
But if I try looking for enabled accounts only, like so:
$filter = "(&(msExchMailboxguid=*)" "(facilityID=12345)" "(enabled=$true)" "(|(jobCodeID=0001)" "(jobCodeID=0002)" "(jobCodeID=0003)(jobCodeID=0004)" "(jobCodeID=0005)" "(jobCodeID=0006)))"
It either fails with "the search filter can not be recognized," or it returns nothing at all depending on whether there are 3 or 4 closed parentheses. I've tried a bunch of variations like (enabled=true)
, (enabled -eq true)
but none of them work.
CodePudding user response:
The issue is that you are using an LDAP filter which is different than a native PowerShell filter and so has a different syntax. Even though most LDAP fields match pretty closely to their normal names, the Enabled field is not stored as a "normal" property (e.g. boolean true/false). Instead, it is held in a part of a bitmasked property userAccountControl
. That means you have to use the "intuitive" filter:
(!(userAccountControl:1.2.840.113556.1.4.803:=2))
To filter out only the enabled accounts.
So that makes your filter for your example to become:
$filter = "(&(msExchMailboxguid=*)" "(facilityID=12345)" "(!(userAccountControl:1.2.840.113556.1.4.803:=2))" "(|(jobCodeID=0001)" "(jobCodeID=0002)" "(jobCodeID=0003)(jobCodeID=0004)" "(jobCodeID=0005)" "(jobCodeID=0006)))"