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

Robert Perez-Corona
Robert Perez-Corona used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jose Gabriel Ortega CastroTop Rated Freelancer on MS Technologies
Awarded 2018
Distinguished Expert 2018

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

You can search the users using either samaccountname or email.
Hi Robert,
try the below w/ one user first, once confirmed works. you can add the rest of the users
$users = Get-Content 'C:\temp\email-list.txt'
$targetmembergroup = "group_target_goes_here"
foreach ($user in $users){
    try{
        $ntuser = (Get-ADUser -Filter {userprincipalname -eq $user}).SamAccountName
        Add-ADGroupMember -Identity $targetmembergroup -Members $ntuser -Verbose
        Start-Sleep -s 2
    }catch{
         Write-Host -ForegroundColor Red -BackgroundColor Black  "$($_.Exception.Message)"
         Start-Sleep -s 2        
    }    
}
Write-Host -ForegroundColor Green "Script COmplete!"

Open in new window

Robert Perez-CoronaSystems Administrator

Author

Commented:
Thank you for the help!
Robert Perez-CoronaSystems Administrator

Author

Commented:
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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial