简体   繁体   中英

Find AD-user by Email

I'm trying to get users from active directory, who have a certain email address.

I've got a CSV-File, which contains the emails.

$data = import-csv -path .\are.csv -delimiter +
foreach($i in $data) 
{
    get-aduser -filter {UserPrincipalName -like '$i.email'} 
}

My problem is, that I don't get any output. No error, no data. When I replace $i.email with one of the email addresses, I get the right user information for the one user. So hard coding works.

When I do:

foreach($i in $data)
{
   $i.email
}

I get a list of all the emails.

What is wrong with the code?

Your variable is within single quotes thus doesn't get populated . You have to three options to fix that:

Use double quotes with a sub expression $() :

UserPrincipalName -like "$($i.email)"

Just omit the quotes:

UserPrincipalName -like $i.email

And finally you could use a format string (even with single quotes):

UserPrincipalName -like ('{0}' -f $i.email)

Here is an example to demonstrate what actual value gets passed using the Write-Host cmdlet:

$data = 
@'
email, id
myname@web.de, 1
'@ | convertfrom-csv

foreach($i in $data) 
{
    Write-Host '$i.email'  # This is your current approach
    Write-Host "$($i.email)"
    Write-Host $i.email
    Write-Host ('{0}' -f $i.email)
}

Output:

$i.email # This is the output of your current approach
myname@web.de
myname@web.de
myname@web.de

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM