Search code examples
powershellactive-directory

Powershell to pull properties based on multiple criteria


I am trying to get a list of AD users who have no manager listed and a value of Employee in a custom field usertype.

When I run this, it does not filter but gives me all accounts - users, resources, etc. I can add usertype or manager to the select fields and see that it isn't pulling correctly (manager is populated or usertype is not Employee).

What do I need to change to get the correct data?

Get-ADUser -Filter * -Properties * |  Select Name, SamAccountName, Department 
where-object userType -eq 'Employee' -and Manager -eq $null

Solution

  • If the custom userType attribute is indexed, then in both cases you can leverage the Active Directory Filter:

    Get-ADUser -LDAPFilter "(&(!manager=*)(userType=Employee))" -Properties Department |
        Select-Object Name, SamAccountName, Department
    

    To give a brief explanation on what the LDAP Filter is doing:

    (&                       # AND, all conditions must be met
        (!manager=*)         # manager attribute is not populated
        (userType=Employee)  # usertype attribute is equal to "Employee"
    )                        # close then AND clause
    

    If the custom attribute is not indexed, then the filtering must be done with PowerShell:

    Get-ADUser -LDAPFilter "(!manager=*)" -Properties Department, userType |
        Where-Object userType -EQ 'Employee' |
        Select-Object Name, SamAccountName, Department
    

    If you also need to find Enabled users only then you can include the following to your filter:

    Get-ADUser -LDAPFilter "(&(!manager=*)(!userAccountControl:1.2.840.113556.1.4.803:=2))" -Properties ...
    

    As for why your code is failing, you have a missing pipe after your Select-Object statement and when filtering for multiple conditions with Where-Object, we must use a scriptblock. In conclusion, the following would've worked (but a lot slower than the above examples).

    Get-ADUser -Filter * -Properties Department, userType, Manager |
        Where-Object { $_.userType -eq 'Employee' -and -not $_.Manager } |
        Select-Object Name, SamAccountName, Department