Add users to security group from csv

Hi,
I tried the script, it adds the users which are in first line  in the CSV, however when I have users more than one, it gives the following error:

adding users to group "narasimha.s"
 - Cannot find an object with identity: '' under: 'DC=test,DC=local'.

CSV format:
Group                                                                      Samaccount
DL-WGK-US-Houston-Projects-XXXXXX-RW           Test102
                                                                              GG-WGP-US-test-Projects-XXXXXX-RO-TEST
                                                                              Narasimha.S



Import-Module ActiveDirectory
Import-Csv "C:\Users\a.narasimha.s\Desktop\Project folder creation\Adduserstogroup.txt" |
 ForEach `
 {
   $users = @($_.samAccount -split ",")
   $group = $_.group
   write-output "adding users to group ""$group"""
   #$users
   $users |
    ForEach `
    {
      try
      {
        $user = $_
        Add-ADGroupMember -Identity $group -Members $user
      }
      catch
      { Write-Output "$user - $($error[0].exception.message)" }
    }
 }

Open in new window

LVL 3
SAM ITAD windows Admin Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Alex GreenProject Systems EngineerCommented:
Do you want to add multiple users to a single group or multiple groups and multiple users?

Import-module ActiveDirectory 
Import-CSV "C:\Scripts\Users.csv" | % { 

Add-ADGroupMember -Identity TestGroup1 -Member $_.UserName 
}

Open in new window

1
SAM ITAD windows Admin  Author Commented:
I need to add multiple users and security groups to one security group
0
SAM ITAD windows Admin  Author Commented:
Input should be from CSV. The mentioned script works fine but it consider only first line in the CSV . It wont consider the samaccount details from the second line
0
Redefine Your Security with AI & Machine Learning

The implications of AI and machine learning in cyber security are massive and constantly growing, creating both efficiencies and new challenges across the board. Check out our on-demand webinar to learn more about how AI can help your organization!

Alex GreenProject Systems EngineerCommented:
Why are you nesting groups like that and then putting in users, that makes no sense at all
0
oBdACommented:
So you don't want to repeat the group name in each line of the csv, but continue with the last one when the the next line contains a user name, but no group name?
Import-Module ActiveDirectory
Import-Csv "C:\Users\a.narasimha.s\Desktop\Project folder creation\Adduserstogroup.txt" | ForEach-Object {
	If ($_.Group) {
		$Group = $_.Group
	}
	$Users = @($_.samAccount -split ",")
	Write-Output "Adding users to group '$($Group)'"
	ForEach ($User In Users) {
		Write-Output "  - '$($User)'"
		Try {
			Add-ADGroupMember -Identity $Group -Members $User -ErrorAction Stop
		} Catch {
			Write-Output "'$($User) - $($Error[0].Exception.Message)"
		}
	}
}

Open in new window

0
SAM ITAD windows Admin  Author Commented:
Got your point.

 Add the users mentioned in the form to the Global  Group and add the Global group to Domainlocal group.
Users requesting for Modify access should add to Global group and Global group should be added to Domain local group
0
SAM ITAD windows Admin  Author Commented:
@obda : Want to add multiple users to security group using csv Input
0
oBdACommented:
That is obvious; but what you posted as a sample is not a csv; based on your editing looks like you have a csv where the group name is not set in every row, indicating that the last available group name should be used for rows without group name.
In other words, a csv like this (spaces added for clarity):
"Group",     "Samaccount"
"Group1",    "Member1Group1"
"",          "Member2Group1"
"",          "Member3Group1"
"Group2",    "Member1Group2"
"",          "Member2Group2"

Open in new window

If so, the script I posted above should be able to do this.
If not, please attach the actual csv you're using, or post it inside [code][/code] blocks, without format changes (so no removal of delimiters, no adding of spaces etc.).
0
SAM ITAD windows Admin  Author Commented:
@OBDA

Getting error If I used the script you have mentioned above
Error screen shot  and CSV also attached
error.jpg
new.csv
0
oBdACommented:
That's just a missing $ in front of "Users" in line 8, sorry; just add it.
And with the csv attached, neither mine nor your script would work. It would create objects with the properties
"Group",
"Samaccount"
and the group name would need to retrieved using something like $_.'"Group",' and be
"DL-WGP-US-H-Projects-XXXXXX-RO-TEST",
(Quotes and trailing commas included!).
The csv should look like that:
"Group","Samaccount"
"DL-WGP-US-H-Projects-XXXXXX-RO-TEST","Global-WGP-US-H-Projects-XXXXXX-RO-TEST"
"","test102"
"","narasimha.s"
"","Mohan.Raj"

Open in new window

Technically, PS would accept this as well:
Group,Samaccount
DL-WGP-US-H-Projects-XXXXXX-RO-TEST,Global-WGP-US-H-Projects-XXXXXX-RO-TEST
,test102
,narasimha.s
,Mohan.Raj

Open in new window

The double quotes around the fields are only required if the field text contains the delimiter itself.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SAM ITAD windows Admin  Author Commented:
0
Jason CrawfordTransport NinjaCommented:
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Accept: oBdA (https:#a42088526)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

exchangepro
Experts-Exchange Cleanup Volunteer
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.