2020 年 6 月 3 日

IT Skills 波林

Polin WEI – 資訊工作者的技術手札

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

1 min read
ariplane

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

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

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

有兩種寫法, 第一種

#fromEmailInport1.ps1
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 $_ }
}

第二種

#fromEmailImport2.ps1
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)"
  }
}

 

 

Copyright © All rights reserved. | Newsphere by AF themes.