0

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.

2
  • 1
    I'm a little confused about your csv format. What are the headers and how many headers do you have? Commented Jun 14, 2019 at 8:18
  • They are - Username,FACULTY01,FACULTY02,FACULTY03,FACULTY04, total 5 Commented Jun 16, 2019 at 23:37

1 Answer 1

2

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @mhu that looks much more precise than what I had but now I'm having a slightly different error - seems the parameter cannot be found @ line 2 "Import-Csv : A positional parameter cannot be found that accepts argument 'System.Object[]'
Sorry, forgot the brackets, see answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.