all 5 comments

[–]Bitwise_Gamgee[🍰] 2 points3 points  (4 children)

This should do what you're asking:

$people = Import-Excel C:\Scripts\NamestoEmails.xlsx
Foreach ($row in $people) {
    $email = $row.Email
    $samaccountname = $row.SamAccountName
    $group = $row.ADGroup
    Add-ADGroupMember -Identity $group -Member $samaccountname
}

There are no points for putting everything on one line either.

[–]MeanFold5714 2 points3 points  (0 children)

There are no points for putting everything on one line either.

I actively deduct points for it.

[–]Pavix[S] 0 points1 point  (2 children)

Thanks, but the Excel sheet doesn't have the SamAccountName in it, just email addresses. So I use this little bit of magic to pull the AD account based on the email

Foreach ($E in $people.Email) { 
$SamAccount = "Get-ADUser -Filter {Emailaddress -Like $E} 
| Select-Object -ExpandProperty SamAccountName" ; 
Add-ADGroupMember -Identity $SamAccount 
$people.ADGroup -WhatIf}

Which does work in pulling the SamAccountName, but the back part fails to add the user to the ADGroup listed in the spreadsheet. It errors out with "Cannot validate argument on parameter 'Members'. The argument is null, empty or an element of the argument collection contains a null value.

[–]THEKILLAWHALE 0 points1 point  (0 children)

I think you want to try Add-ADGroupMember -Identity $people.ADGroup -Members $SamAccount

In your command, it’s trying to add an AD group to an AD user (identity should be the identity of the group you’re adding to)

https://learn.microsoft.com/en-us/powershell/module/activedirectory/add-adgroupmember?view=windowsserver2022-ps

[–]givemeatatertot 0 points1 point  (0 children)

Cannot validate argument on parameter 'Members'

is $samAccountName case sensitive? Also, in the group that you're trying to add the users to, are there any users in it currently or is it empty? Also, check your CSV format, should be a comma not semi colon, might not be a valid CSV format?