简体   繁体   中英

Get-ADUser -LDAPFilter accepting wrong LDAP query in the System.Management.Automation library (C#)

I'm using the System.Management.Automation library to extract users from an AD in my application. Which users are extracted is done by specifying the LDAP query in Get-ADUser -LDAPFilter , but first I validate the LDAP query to make sure it is valid like this:

public static bool ValidLDAPQuery(string ldapQuery)
{
    try
    {
        using (var powerShell = PowerShell.Create())
        {
            var adUsersList = powerShell
                 .AddCommand("Get-ADUser")
                 .AddParameter("LDAPFilter", ldapQuery)
                 .Invoke();
        }
    }
    catch (Exception)
    {
        return false;
    }

    return true;
}

The thing is that wrong LDAP queries passed to this method are accepted in normal PowerShell. For instance this query (&(objectClass=user)(objectCategory=person)(!BLABLABLAObject=*)) would work, but of course the return count would just be 0 . It only throws an error if the parenthesis is uneven or when the Key=Value search is not written properly.

Is there a way to make it throw an error if any part of the query is wrong (not taking into account parenthesis and equal signs)?

Thanks to Bill_Stewart for the clarification. I'll just write the clarification he wrote in the comments above as an answer just in case it goes unnoticed.

So the command will throw an error when a wrongly written LDAP query is passed to the method parameter, such as (&(objectClass=user objectCategory=person)(!CriticalObject=* . But it will not reject the query if the attributes or values specified do not exist, (&(objectClass=user)(objectCategory=person)(!BLABLABLAObject=*)) for instance, it will simply yield not results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM