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 comparisonWhen 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With