You need to first resolve the ADUser
object matching that email address, the -Identity
parameter won't auto-resolve based on the EmailAddress
field of an ADUser
. Assuming the EmailAddress
property is set appropriately on the user object in AD, and assuming the column name for the email address in your CSV is ExternalEmailAddress
, this should work:
Import-CSV "C:\users\user\desktop\test1.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)"
}
}
Note that if the ADUser does not have the email address set, you will not be able to match that AD user to an email.
Here are the docs for Add-ADGroupMember
, you may want to read up on them for more information: https://learn.microsoft.com/en-us/powershell/module/activedirectory/add-adgroupmember?view=winserver2012-ps&viewFallbackFrom=winserver2012r2-ps
EDIT: Found some strangeness with using brackets and the $PSitem, so I changed it to use a string-based filter.
EDIT 2: Found the cause for why using a variable in a bracket-based -Filter
doesn't work (which is how I had originally written this), and in fact is not recommended when scripting: Get-Aduser -Filter will not accept a variable
Get-Help Add-ADGroupMember -Detailed
– Stenotype