Adding ADusers to ADGroups

I have a CSV with 23 AD users and each is assigned a different group. I am trying to assign the user to the group. The following script works but I think there is a better way to cycle through each user and group. Maybe with a Hash table? Thanks! Bill

Example

user1,group1

user2,group2

 

[pre]
Clear-Host

$varAccounts = Import-Csv C:\temp\Accounts.csv

$UserAccounts = $varAccounts.Account
$UserGroups = $varaccounts.group

$varcount=0
$varcounts = $varAccounts.Length

while ($varcount -lt $varcounts) {

Add-ADPrincipalGroupMembership -Identity $UserAccounts[$varcount] -MemberOf $UserGroups[$varcount]
$varcount += 1
}
[/pre]

First I would advice you to add column names to your CSV file.

user;group
user1;group1
user2;group2

Then, here is the code I would use

$AccountList = Import-Csv -Path C:\temp\Accounts.csv

foreach($Account in $AccountList){
    
    Add-ADPrincipalGroupMembership -Identity $Account.User -MemberOf $Account.Group
}

But a one-liner is also possible

Import-Csv -Path C:\Temp\Accounts.csv | ForEach-Object -Process {Add-ADPrincipalGroupMembership -Identity $PSItem.User -MemberOf $PSItem.Group}

Or even shorter but quick and dirty with Add-ADGroupMember instead of Add-ADPRincipalGroupMembership

Import-Csv C:\Temp\Accounts.csv | % {Add-ADGroupMember $_.Group $_.User}

Thanks, that worked. I was having issues figuring out how to loop through two different variables but that makes sense.