Whenever I work with Active Directory and I want to use pretty complex LDAP Filter to search for objects I’m after I’m tempted to use line break here and there to make whole thing easier on eyes of future reviewer (even if the only person to read the code is me “few weeks later”).
The problem is that AD won’t understand filter that looks like that:
$LDAPFilter = @' (& (name=b*) (givenName=b*) ) '@
It won’t fail, you won’t get an error, it just won’t work. What I usually do is just use –join operator on array that looks very similar to above here-string:
$LdapFilterJoined = -join @( '(&' '(name=b*)' '(givenName=b*)' ')' )
Another options is just remove any whitespace from here-string that we created at first:
$FilterFixed = $LDAPFilter -replace "\s" ([adsisearcher]$FilterFixed).FindOne()
End result in either case should be similar:
For simple filters it doesn’t make sense to break anything into several lines, it’s obvious what will happen anyway. But if you mix several conditions in single LDAP Filter (AND and ORs), than it’s convenient to have each group presented in clear format. E.g.:
$MonthAgo = (Get-Date).AddDays(-30).ToFileTime() ( [ADSISearcher]( -join @( '(&' '(!userAccountControl:1.2.840.1135184.108.40.2063:=2)' '(|' '(name=b*)' '(givenName=b*)' ')' "(lastLogonTimeStamp>=$MonthAgo)" ')' ) ) ).FindAll()
Obviously, using single-line syntax would be as effective as this one. The only difference is than now I have no problem to tell which conditions have to be met (&) and what is optional (|).