Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 625
15433 Avatar asked Sep 15 '25 15:09

15433


2 Answers

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
like image 128
Itchydon Avatar answered Sep 18 '25 10:09

Itchydon


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

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

like image 38
Theo Avatar answered Sep 18 '25 08:09

Theo