Hey I've got this cmdlet here:

Get-ADUser -filter {(distinguishedName -notlike "Disabled Users") -and (enabled -eq $false)} -searchBase "ou=FirstOU,dc=domain,dc=com"

I've built it to find disabled users that are not in the "Disabled Users" OU. (an OU within an OU)

But for some reason it returns not only the disabled users that are not in "Disabled Users", but the disabled users that are in it as well.

Why doesn't (distinguishedName -notlike "Disabled Users") work?

To make my structure clear:

       Disabled Users OU

Brackets and wildcards. Try

PS C:\Users\BigHomie> Get-ADUser -SearchBase "OU=Users,dc=eng,dc=mit,dc=edu" -SearchScope Subtree -Filter {distinguishedname -notlike "*Disabled*"}

Proper Syntax was found here

| improve this answer | |
  • 1
    it's all good ;) – MDMoore313 Jun 4 '14 at 13:14
  • It does not output anything.. although I do have some users that should come out.. – Npv23g Jun 4 '14 at 13:20
  • haha, perhaps your oneliner works as intended, and there are no disabled users outside the disabled OU? – MDMoore313 Jun 4 '14 at 13:22
  • @BigHomie nope. I have some disabled users that arent inside my Disabled Users OU. – Npv23g Jun 4 '14 at 13:41
  • did you set your -SearchScope to Subtree? – MDMoore313 Jun 4 '14 at 13:42

The filter acts on the type of object you are trying to retrieve, in this case a User object. Thus your query is returning any disabled users where the dn is not "Disabled Users". It is applying the filter to the User objects, not the OUs.

Yes, of course... The User dn will contain the string "Disabled Users" as BigHomie correctly pointed out. The real problem was the lack of wildcard characters, since the User dn will not be exactly "Disabled Users"

Try this instead:

Get-ADUser -Filter  {(Enabled -eq $false)} | ? { ($_.distinguishedname -notlike '*Disabled Users*') }
| improve this answer | |
  • So how can I do it? – Npv23g Jun 4 '14 at 13:03
  • 1
    But the dn of the user contains the parent OU – MDMoore313 Jun 4 '14 at 13:07
  • 1
    Dang it, beat me with the edit! :) Yeah, I'd grab all the users first, and then filter with Where-Object as well. – jscott Jun 4 '14 at 13:10

Your query doesn't work because DN attributes doesn't support wildcard matching in LDAP queries (and -like/-notlike is useless without wildcards).

You'll simply have to retrieve all disabled users and then filter the unwanted accounts out from the result:

$Disabled = Get-ADUser -Filter { useraccountcontrol -bor 2 } -SearchBase "ou=FirstOU,dc=domain,dc=com"
$Filtered = $AllDisabledUsers |Where-Object {$_.distinguishedName -notmatch "OU=Disabled Users"}

The { useraccountcontrol -bor 2 } is equivalent to a "pure" LDAP filter for disabled accounts:

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.