利用 PowerShell Script 將email 帳號加入群組

62 / 100

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

準備 Users.csv 檔, 內容如下:

# Users.csv
[email protected]
[email protected]
[email protected]
[email protected]

有兩種寫法, 第一種

ForEach ($item in (Import-CSV Users.csv)) {
  $email = $item.'EmailAddress' #whatever your field name
  Get-ADUser -Filter "mail -eq '$email'" | 
  % { Add-ADGroupMember -Identity 'Test Group' -Members $_ }


Import-CSV "Users.csv" | Foreach-Object {
  $aduser = Get-ADUser -Server localhost -Filter "EmailAddress -eq '$($_.EmailAddress)'"
  if( $aduser ) {
    Write-Output "Adding user $($aduser.SamAccountName) to groupname"
    $adGroup = Get-ADGroupMember -Server localhost -Identity 'TestGroup'
    Add-ADGroupMember -Server localhost -Identity 'TestGroup' -Members $aduser
  } else {
    Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"