header image

Using GivenName and Surname instead of samAccountName

Posted by: | December 29, 2014 Comments Off on Using GivenName and Surname instead of samAccountName |

A recent comment on this post – https://richardspowershellblog.wordpress.com/wp-admin/post.php?post=2762&action=edit – asked about using the given name and surname rather than the samAccountName in Get-ADUser.

Get-ADUser has 4 options when using the –Identity parameter:

Account name = samAccountNmae

Distinguished Name

GUID

Security identifier = SID.

Using the given name and surname. on the surface doesn’t seem possible BUT (and there’s always a but with PowerShell) you can use the –Filter or –LDAPFilter parameters.

 

Where you know the samAcccountName you can do this:

Get-ADUser -Identity gdreen

 

Working with the names you could try this:

Get-ADUser -Filter {GivenName -eq ‘Dave’ -and Surname -eq ‘Green’}

 

Alternatively, you could use an LDAP filter:

Get-ADUser -LDAPFilter "(&(GivenName=Dave)(Sn=Green))"

 

The LDAP syntax is a bit more complex but you can parse it as

(GivenName=Dave) AND (Sn=Green)

You have to use the LDAP name, Sn, for the Surname property rather than the more friendly property name that the –Filter parameter allows.

 

If you wanted to modify the code in the original article to use this approach:

$users = Import-Csv -Path C:\Scripts\adtest.csv           
           
foreach ($user in $users) {           
$fname = $user.GivenName
$lname = $user.Surname
 
Get-ADUser -Filter {GivenName -eq $fname  -and Surname -eq $lname} -Properties * |           
select SamAccountName, Division, Office, City            
}

 

I’ve found that its easier to substitute variables into the filter rather than try and and use the object from the CSV file directly.

 

The LDAP filter version would be

$users = Import-Csv -Path C:\Scripts\adtest.csv           
           
foreach ($user in $users) {           
 
Get-ADUser -LDAPFilter "(&(GivenName=$($user.GivenName))(Sn=$($user.Surname)))" -Properties * |            
select SamAccountName, Division, Office, City            
}

 

In this case you’re substituting into a string and it works quite nicely.

under: PowerShell and Active Directory

Comments are closed.

Categories