Add multiple users to multiple groups from one import csv

北城余情 提交于 2019-11-29 11:28:36

Change this:

add-adgroupmember -identity $_.Group -member $_.Accountname

To this:

add-adgroupmember -identity $user.Group -member (Get-ADUser $user.Accountname)

@EBGreen has answered what's wrong with your code. Just coming up with an alternative here. Instead of running the command once per member, you can try to add all members of a group at the same time. The Member parameter supports an array, so try this:

Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % {
    #Foreach Group, get ADUser object for users and add members
    $users = $_.Group | % { Get-ADUser $_.Accountname }
    Add-ADGroupMember -Identity $_.Name -Member $users
}

EDIT I've sucessfully tested this on 2012 DC with following content in test.csv (values represent existing group name and existing samaccountname/username):

Group,Accountname
"Mytestgroup","kim_akers"
"Mytestgroup","user1"

EDIT2 It shouldn't have any problems with deeper level OUs. I tested with an OU that was 7 levels deep and it had no problem. If you have all the user inside one OU (or find the closest OU that contains all the sub-OUs), see if this script helps. Remember to replace DN for "base OU" in -Searchbase parameter.

Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % {
    #Foreach Group, get ADUser object for users and add members
    $users = $_.Group | % { Get-ADUser -Searchbase "OU=mybaseou,OU=test,OU=users,OU=contoso,DC=Contoso,DC=com" -Filter { samaccountname -eq $_.Accountname } }
    Add-ADGroupMember -Identity $_.Name -Member $users
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!