Reputation: 45
I'm trying to add multiple users to multiple groups from a csv file and have looked through every post about adding multiple users to multiple groups for the past weeks but due to the nature of csv file I am having trouble executing it correctly.
The data in the csv file looks like this
Username,FACULTY01,FACULTY02,FACULTY03,FACULTY04
"User1,group1,group2,group3"
"User2,group1,,group3,group4"
"User3,,group2,,group4"
There are 20+ groups, each member can be part of 1 to 4 groups found under the faculty headings
I have the following code
Import-Module ActiveDirectory
$csv = Import-csv C:\TestADGroupADD.csv -Header ('Username', 'FACULTY01', 'FACULTY02', 'FACULTY03', 'FACULTY04')
ForEach-Object {
$username = $_.Username
$Faculty = $_."Faculty01,FACULTY02,FACULTY03,FACULTY04"
}
Foreach($Faculty in $csv){
if ($Faculty -eq 'ADMINISTRATION') { Add-ADGroupMember -Identity $Faculty -Member $username }
if ($Faculty -eq 'Accounting') { Add-ADGroupMember -Identity $group -Member $username }
if ($Faculty -eq 'SCIENCE') { Add-ADGroupMember -Identity $group -Member $username }
if ($Faculty -eq 'SALES') { Add-ADGroupMember -Identity $groupe -Member $username }
if ($Faculty -eq 'DEANSFUND') { Add-ADGroupMember -Identity $group -Member $username }
}
I have a feeling I must use a different method to combine the faculties into one variable but I have tried with one and still fails - I am a beginner in PowerShell
Appreciate your help.
Upvotes: 0
Views: 757
Reputation: 18061
You could do something like this:
$faculties = @("FACULTY01", "FACULTY02", "FACULTY03", "FACULTY04")
$csv = Import-csv C:\temp\test.csv -Header (@("UserName") + $faculties)
foreach ($user in $csv | Select-Object -Skip 1)
{
foreach ($faculty in $faculties)
{
if ($user.$faculty)
{
Add-ADGroupMember -Identity $user.$faculty -Member $user.UserName
}
}
}
Upvotes: 2