简体   繁体   中英

Get email address from Samaccountname

I am a beginner to power shell . I need to write a command for getting the email addresses from samccountname from active directory . I have stored all the samaccountnames in Users.txt file.

$users=Get-content .\desktop\users.txt
get-aduser -filter{samaccountname -eq $users} -properties mail | Select -expandproperty mail 

Kindly suggest me how to go forward with this. What is the thing i am doing wrong here.

After reading it in from the file, $Users becomes a collection of users. You can't pass that entire collection in to the filter, you need to handle it one user at a time. You can do this with a ForEach loop:

$users = Get-Content .\desktop\users.txt
ForEach ($User in $Users) {
    Get-ADUser -Identity $user -properties mail | Select -expandproperty mail
}

This will output each users email address to the screen.

Per the comments, its also unnecessary to use a -filter for this, per the above you can just send the samaccountname directly to the -Identity parameter instead.

If you want to send the output on to another command (such as export-csv) you could use ForEach-Object instead:

$users = Get-Content .\desktop\users.txt
$users | ForEach-Object {
    Get-ADUser -Identity $_ -properties mail | Select samaccountname,mail
} | Export-CSV user-emails.txt

In this example we use $_ to represent the current item in the pipeline (eg the user) and then we pipe the output of the command on to Export-CSV. I thought you might also want this kind of output to have both samaccountname and mail so that you could cross-reference.

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