问题
Import-CSV "C:\users\Balbahagw\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 tech-103 -Members $aduser
} else {
Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
}
}
Script is working now, however it can't find the user in AD with the email address.
回答1:
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://docs.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
来源:https://stackoverflow.com/questions/51108536/powershell-script-to-add-users-to-a-d-group-from-csv-using-email-address-only