Powershell script to add users to A/D group from .csv using email address only?

泪湿孤枕 提交于 2019-12-11 12:59:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!