0
votes

I'm struggling with getting the SamAccountName from AD by searching with the email address. I have a CSV that contains email addresses but need to get the SamAccountName. "write-host $user.EmailAddress" prints the email address correctly, Get-ADuser is not giving any errors but "write-host $CurrentUser" prints an empty line

foreach($user in $users)
{
write-host $user.EmailAddress
    #$CurrentUser = Get-ADUser -filter "EmailAddress -eq '$($user)'"
    #$CurrentUser = Get-aduser -Filter { "mail -eq '$($user.EmailAddress)'"} -Properties mail
    $CurrentUser = Get-ADUser -Filter { mail -eq "$($user.EmailAddress)"} -properties SamAccountName
    write-host $CurrentUser

I've tried a few different snippets I found online but just can't get it to work

Powershell version: 5

1
if you manually run Get-ADUser with just one entry from the $Users list, does it work?Lee_Dailey
The syntax -Filter "property -operator 'value'" always worksAdminOfThings

1 Answers

0
votes

Give yourself a break on the black magic of active directory filters. Trying to get the quoting right for "$object.property" is just too much trouble. The truth is, it's trial and error, and no one understands how it works. The type of -filter isn't even scriptblock but string, but even the docs seem to expect you to pass it as scriptblock. See the Backus-Naur form under -Filter in the docs. https://docs.microsoft.com/en-us/powershell/module/addsadministration/get-aduser?view=win10-ps

$emailaddress = $user.emailaddress
get-aduser -filter { mail -eq $emailaddress }