3

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:

Forest
    FirstOU
       users,groups,etc..
       Disabled Users OU
.
.
.
squillman
  • 37,883
  • 12
  • 92
  • 146
Npv23g
  • 320
  • 4
  • 6
  • 12

3 Answers3

2

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*') }
squillman
  • 37,883
  • 12
  • 92
  • 146
2

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

MDMoore313
  • 5,581
  • 6
  • 36
  • 75
2

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:
(&(useraccountcontrol:1.2.840.113556.1.4.803:=2))

Mathias R. Jessen
  • 25,161
  • 4
  • 63
  • 95