Forum Discussion
Tim_Opie
Mar 08, 2023Copper Contributor
Adding B2B guests and adding to security group
Hi, New-ish to Powershell so hoping this isn't a dumb question. It all seems to work as parts but wont run as a whole. The inviting the guest works, just wont add the user to the test security g...
Varun_Ghildiyal
Mar 09, 2023Iron Contributor
Hello!
From what I can see, the issue is likely related to the fact that the Add-AzureADGroupMember command is running outside of the foreach loop. This means that it's trying to add the user to the group using the last value of $email.Name, which is likely not what you intended.
To fix this, you should move the Add-AzureADGroupMember command inside the foreach loop, like this:
$invitations = import-csv C:\B2BUploads\Test.csv
$messageInfo = New-Object Microsoft.Open.MSGraph.Model.InvitedUserMessageInfo
$messageInfo.customizedMessageBody = "Welcome message"
$GroupID = ((Get-AzureADGroup -Filter "Displayname eq 'Test'").ObjectID)
foreach ($email in $invitations) {
New-AzureADMSInvitation `
-InvitedUserEmailAddress $email.InvitedUserEmailAddress `
-InvitedUserDisplayName $email.Name `
-InviteRedirectUrl https://sharepoint site here `
-InvitedUserMessageInfo $messageInfo `
-SendInvitationMessage $true
Add-AzureADGroupMember `
-ObjectId $GroupID `
-RefObjectID ((Get-AzureAdUser -All $true | Where-Object {$_.DisplayName -in $email.Name}).ObjectID)
}
This should ensure that the Add-AzureADGroupMember command is run once for each email address in the CSV file, using the correct value of $email.Name each time.