header image

Searching Active Directory by email address

Posted by: | November 21, 2019 Comments Off on Searching Active Directory by email address |

I was asked recently about searching Active Directory by email address and returning the first and last names of the users.

First off I needed to populate the first and last name and email fields as they weren’t set in my test domain

Get-ADUser -Filter * -SearchBase ‘OU=UserAccounts,DC=Manticore,DC=org’ |
foreach {
$names = $_.Name -split ‘ ‘

Set-ADUser -Identity $_.DistinguishedName -EmailAddress $_.UserPrincipalName -GivenName $names[1].Trim() -Surname $names[0].Trim()

}

 

Get the users in the UserAccounts domain. Split the name and use that information to set the first (GivenName) and last (Surname) properties. Use the UserprincipalName for the email address.

 

Now create a CSV file with the email addresses

PS>  Get-ADUser -SearchBase ‘OU=UserAccounts,DC=Manticore,DC=org’ -Filter * -Properties EmailAddress | select -Property  EmailAddress | Export-Csv -Path C:\Test\addresses.csv

 

Test the file

PS>  Import-Csv -Path C:\Test\addresses.csv

 

You can’t use the –Identity property when you’re searching by email address. You have to use a filter:

PS>  Get-ADUser -SearchBase ‘OU=UserAccounts,DC=Manticore,DC=org’ -Filter {EmailAddress -eq ‘DorothyJones@manticore.org’}

 

Or LDAP filter

PS>  Get-ADUser -SearchBase ‘OU=UserAccounts,DC=Manticore,DC=org’ -LDAPFilter “(objectclass=user)(mail=DorothyJones@manticore.org)”

 

The difference is that the filter uses the AD cmdlet name for the property but the LDAP filter uses the LDAP name of the proeprty

 

To read the email addresses and find the corresponding names using a filter

Import-Csv -Path C:\Test\addresses.csv |
ForEach-Object {
$address = $_.EmailAddress
$user = Get-ADUser -SearchBase ‘OU=UserAccounts,DC=Manticore,DC=org’ -Filter {EmailAddress -eq $address}

$props = [ordered]@{
FirstName = $user.GivenName
Lastname = $user.Surname
Email = $_.EmailAddress
}
New-Object -TypeName PSobject -Property $props
}

 

Import the addresses. I’ve found it less error prone to create a variable to handle the value I’m searching for rather than trying to substitute into the filter. Once you have the account create the output object.

 

Using an LDAP filter is similar

Import-Csv -Path C:\Test\addresses.csv |
ForEach-Object {
$address = $_.EmailAddress
$user = Get-ADUser -SearchBase ‘OU=UserAccounts,DC=Manticore,DC=org’ -LDAPFilter “(objectclass=user)(mail=$address)”

$props = [ordered]@{
FirstName = $user.GivenName
Lastname = $user.Surname
Email = $_.EmailAddress
}
New-Object -TypeName PSobject -Property $props
}

 

The choice between a filter and an LDAP filter is up to you. Both have quirks and are probably equally awkward to use.

under: PowerShell and Active Directory

Comments are closed.

Categories