PowerShell Add users to AD group from CSV via email

PowerShell Add users to AD group from CSV via email

In this article, we will discuss how to add users to AD group from CSV using their email addresses. This script queries the user’s email address instead of the user principal name, which is very helpful in environments where the user’s email address doesn’t match the UPN.

Prepare CSV with Users’ Email Address

The first step is to create a CSV with the user’s email address and correct header. Open Notepad and enter “EmailAddress” in the first line, CSV’s header.

EmailAddress
User1EmailAddress
User2EmailAddress

I have created a new folder where this CSV file will be saved. “C:\PSData” and this location will be used in the PowerShell script. Please feel free to create the same folder structure or use a different location and modify the CSV location in the PowerShell script

Get AD Security Group Name From Active Directory

Open Active Directory Users and computers console, find the security group would want to import users to and copy the group name.

Add users listed in CSV to the AD Security group using PowerShell Script.

Copy below PowerShell Scrip by clicking on copy button on top. Open PowerShell ISE as Administrator and paste the below code into the script block. Replace ‘AdGroupName’ with your AD Group Name and change location of CSV if you are using different location

# Import AD Module
Import-Module ActiveDirectory

# Please replace 'ADGroupName' below with AD Security group
$GroupName = 'ADGroupName'

# Please enter correct CSV location, this PowerShell Script is using "C:\PSData\UserList.csv"
$Users = Import-Csv "C:\PSData\UserList.csv"
Import-CSV -path "C:\PSData\UserList.csv" | Foreach-Object {
  $aduser = Get-ADUser -Filter "EmailAddress -eq '$($_.EmailAddress)'"
  if( $aduser ) {
    Write-Output "Adding user $($aduser.SamAccountName) to $GroupName"
    Add-ADGroupMember -Identity $GroupName -Members $aduser
  } else {
    Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
  }
}

Verify PowerShell script successfully added users to AD Security Group

Please check the Members tab of the AD security group to verify users have been added.

Conclusion

In this article, we have discussed how to add users to AD security group from CSV using the users’ email addresses.

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *