Link to home
Start Free TrialLog in
Avatar of Robert Perez-Corona
Robert Perez-CoronaFlag for United States of America

asked on

Powershell script to add users into a group in Active Directory using their email addresses

I am trying to get the script below to Import a list of user emails from a txt files, then provide me with the samaccountname and then inject the samaccount names into an AD distribution list or Sec group.

So far the script generates the Samaccountname. However, I am stuck on the part where the samaccountnames get added to the AD group.

I believe(could be wrong) I can add users to an AD group based on samaccountname but not email addresses. Which is why I am retrieving the samaccountname based on the email to then push them into the AD group.

Get-Content C:\temp\email-list.txt | ForEach {

    Get-ADUser -Filter "mail -eq '$_'" | Select SamAccountName 


Open in new window

Thank you in advance.
Avatar of J0rtIT
Flag of Venezuela, Bolivarian Republic of image

What is the content of your "email-list.txt" ?

You can search the users using either samaccountname or email.
Avatar of ivan rosa
ivan rosa
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Robert Perez-Corona


Thank you for the help!
One quick last question: If I were to Remove user users instead of add; can I simply use the Remove-ADGroupMembership cmdlet?
You would have to incorporate it with this:

Remove-ADGroupMember -Identity  $targetmembergroup member $ntuser -Confirm $false