Powershell – Querying for inactive users from a specific OU using powershell with the help of AD filter and LDAP filter

active-directorypowershell

I am trying to get the list of all inactive members from a specific OU named inactive with the following queries:

(&(objectCategory=person)(objectClass=user)(OU=inactive,OU=Users,OU=Administration,DC=companyname,DC=com)(userAccountControl:1.2.840.113556.1.4.803:=2))

(&(objectCategory=CN=Organizational-Unit,CN=Schema,CN=Configuration,DC=companyname,DC=com)(objectClass=organizationalUnit)(memberOf=OU=inactive,OU=Users,OU=Administration,DC=companyname,DC=com)(userAccountControl:1.2.840.113556.1.4.803:=2))

(&(objectCategory=CN=Organizational-Unit,CN=Schema,CN=Configuration,DC=companyname,DC=com)(objectClass=organizationalUnit)(userAccountControl:1.2.840.113556.1.4.803:= OU=inactive,OU=Users,OU=Administration,DC=companyname,DC=com))

(&(objectCategory=CN=Organizational-Unit,CN=Schema,CN=Configuration,DC=companyname,DC=com)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:= OU=inactive,OU=Users,OU=Administration,DC=companyname,DC=com))

However the search is not returning any record.

The CN for the inactive OU is inactive/USERS/Administration/Companyname.

Whenever I give this path for the inactive OU it does not return any results.

Please let me know how can we get the required results. When I try searching it from the AD console it shows the results as there are 1350 users inactive, but I am trying to incorporate it in a script.

Best Answer

So you want to retrieve the members that are disabled in AD or not?

The disabled users in that ou:

Get-ADUser -Searchbase "OU=inactive,OU=Users,OU=Administration,DC=companyname,DC=com" -LDAPFilter "(!userAccountControl:1.2.840.113556.1.4.803:=2)"

The not-disabled users in that ou:

Get-ADUser -Searchbase "OU=inactive,OU=Users,OU=Administration,DC=companyname,DC=com" -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=2)"

Edit: Even if you are not using the ActiveDirectory-module, the .Net-methods also supports the .searchBase in the form of .searchRoot, but then you would probably need the LDAPfilter:

"(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))"