如何过滤Get-ADObject排除特定对象集合并解决语法错误?
Fixing the Get-ADObject Syntax Error & Excluding Target Objects
Let’s get that AD query working right—syntax errors with LDAP filters are super common, but they’re easy to fix once you know the rules. The issue you’re hitting is almost certainly misaligned parentheses or incorrect logic operator placement in your filter string.
Here’s the Correct Filter to Meet Your Exclusion Requirements
This command will exclude all HealthMailbox-prefixed Exchange monitoring mailboxes, plus any objects in the OU=Disabled Computers and OU=Service Accounts organizational units:
Get-ADObject -Filter "(&(objectClass=*)(!(cn=HealthMailbox*))(!(distinguishedName=*,OU=Disabled Computers,*))(!(distinguishedName=*,OU=Service Accounts,*)))"
Breakdown of the Filter Logic
Let’s unpack each part so you understand why this works:
(&(objectClass=*)): Base condition to match all AD objects (replaceobjectClass=*withobjectClass=userorobjectClass=computerif you only want specific object types).!(cn=HealthMailbox*): Excludes any object where the Common Name starts withHealthMailbox(this targets those Exchange monitoring mailboxes directly).!(distinguishedName=*,OU=Disabled Computers,*): Excludes any object whose full distinguished name contains theOU=Disabled Computerssegment (works regardless of where this OU lives in your domain hierarchy).!(distinguishedName=*,OU=Service Accounts,*): Same logic as above, targeting the service accounts OU.
Common Syntax Mistakes to Avoid
- Unmatched Parentheses: LDAP filters are strict about pairing
(and)—count them carefully to ensure every opening bracket has a closing one. - Incorrect Operator Order: Always wrap combined conditions in
&(AND) or|(OR) at the top level, not scattered inside individual rules. - Misplaced Wildcards: In LDAP,
*only works as a leading or trailing wildcard (you can’t use it in the middle of a string likeHea*lbox). - Unescaped Special Characters: If your OU names had special characters (like commas or ampersands), you’d need to escape them with a backslash—but your current OU names are safe as-is.
Optional: Target Specific Object Types
If you don’t need all AD objects, narrow it down to users and computers with this adjusted filter:
Get-ADObject -Filter "(&(|(objectClass=user)(objectClass=computer))(!(cn=HealthMailbox*))(!(distinguishedName=*,OU=Disabled Computers,*))(!(distinguishedName=*,OU=Service Accounts,*)))"
内容的提问来源于stack exchange,提问作者Senior Systems Engineer
相关产品推荐
相关产品推荐

