简体   繁体   中英

Filter result from Get-ADUser using sAMAccountname

I would like to extract a username from AD using Get-ADUser . The issue I'm having is when using sAMAaccount name as filter, I get multiple results if the value is found in multiple entries. To illustrate, if my samaccountname is 'a123b', and my coworker's is 'c1234d', I get both our names when I run this:

get-aduser -ldapFilter "(samaccountname=*123*)"| select Name

I would like to return only my information based on '123' and not '1234'

I've already tried the following as well to no avail:

get-aduser -Filter "samaccountname -like '*123*'" | select Name

You can narrow it down with a regular expression:

$filter = "[a-zA-Z]123[a-zA-Z]"
Get-ADUser -Filter "samaccountname -like '*123*'" | where { $_.samaccountname -match $filter} | select name
  • $filter is a simple regex pattern looking for 123 surrounded by letters (uppercase or lowercase)
  • -match is the operator that allows a regex comparison

When using a partial SamAccountName in a Filter or LDAPFilter, it is more than likely to get multiple results.

To test and return a specific user account, you need the filter to be more specific if possible (depends on what policies your environment uses for accountnames), like

Get-ADUser -Filter "SamAccountName -like 'a123*'" | Select-Object Name

or use an extra Where-Object clause to narrow down the results by some other user property like the firstname for instance:

Get-ADUser -Filter "SamAccountName -like '*123*'" | Where-Object { $_.GivenName -eq 'John' } | Select-Object Name

Mind you, the above examples can still return multiple user objects..

If you have it, the absolute sure way of retrieving a single user object is by using the DistinghuishedName of that user and get the object by using the -Identity parameter. See Get-ADUSer

PS: When using the -like operator or an LDAPFilter, use wildcard characters on the parts of the name that can vary.

Since you can't use regex in the LDAP query, you could use a query like this to tell it to find user accounts that contain 123 but not with a fourth digit:

(&(objectClass=user)(samaccountname=*123*)(!samaccountname=*1231*)(!samaccountname=*1232*)(!samaccountname=*1233*)(!samaccountname=*1234*)(!samaccountname=*1235*)(!samaccountname=*1236*)(!samaccountname=*1237*)(!samaccountname=*1238*)(!samaccountname=*1239*)(!samaccountname=*1230*))

It's ugly, but it works.

Note that, if you have a filter that starts with a wildcard, the index for that attribute cannot be used, so it will have to look at every account to find a match. I added a filter for objectClass , since that is indexed and it will ensure it only looks at user objects.

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