Add multiple users to AD groups from csv

Good day.

There is a table in * .csv format with correspondence of users to groups in AD [url] group_ad.csv — Yandex.Disk [/ url]

I created groups in AD through a similar csv file.

Caught a stupor when trying to add users to groups in accordance with the table.

The only working option I came up with is to split the table into two:

  1. Table with group names [url] groups_example.csv — Yandex.Disk [/ url]
  2. Table with usernames [url] users_example.csv — Yandex.Disk [/ url]

And with the help of a counter, go through the columns of the table with users and compare each column with a group from the first file.

The solution is crutch, maybe someone faced a similar task and can advise how to make it more beautiful?

I will be grateful.


$Gs = Import-Csv -Path "C:\IT\groups.csv" -Encoding Default -Delimiter ";" 
$Us = Import-Csv -Path "C:\IT\users.csv" -Encoding Default -Delimiter ";" 
#
# Table counter
#
$i=1
ForEach ($G in $Gs) {
$Gr = $G.Group
#
# Search for group in AD
#
$Group = get-adgroup -SearchBase "OU=New Groups,OU=IT,OU=root,DC=smp,DC=loc" -filter 'name -like $Gr'
ForEach ($U in $Us) {
$Users = $U.$i
#
# Search for user in AD
#
$User = Get-ADUser -SearchBase "OU=root,DC=smp,DC=loc" -filter {GivenName -like $Users}
Write-Host $Group.SamAccountName
Write-Host $User.SamAccountName
#
# Add user to group
#
Add-ADGroupMember -Identity $Group.SamAccountName -Members $User.SamAccountName
}
$i++
#$Users = Import-Csv -Path "C:\IT\users_new.csv" -Delimiter ";"
#$Group_Name = Get-ADGroup -Filter {name -like '$Group'} 
#Write-Host $Group_Name
}

Since the -Members parameter on Add-ADGroupMember supports a collection, you only need to do one Add-ADGroupMember per group if you group your users correctly.

1 Like

The biggest issue I see is the format of the csv. Csv is a linear style data structure. A hierarchical structure like an xml or json would be more appropriate. Having said that you can use the member property name to get the groups without resorting to creating two new files. Here’s a solution.

$csv = Import-Csv C:\Users\micha\Downloads\group_ad.csv -Delimiter ";"
$groups = $csv |
   Get-Member -MemberType NoteProperty |
       Select-Object -ExpandProperty "name"

foreach ($group in $groups) {
   $users   = @($csv | Where-Object {$_.$group} | Select-Object -ExpandProperty $group)
   $ADUsers = Get-ADUser -SearchBase "OU=root,DC=smp,DC=loc" -filter {GivenName -in $Users}
   Get-ADGroup -SearchBase "OU=New Groups,OU=IT,OU=root,DC=smp,DC=loc" -filter 'name -like "$group"' | 
       Add-ADGroupMember -Members $ADUsers.SamAccountName
} #foreach group