0

I am running the below script to add users to SharePoint group in SPO sites:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$users= "" 
$users = import-csv D:\User.csv
foreach ($user in $users)
{
$groupname=$user.group
Add-SPOUser -Site $user.SiteURL -LoginName $user.UserEmailAddress -Group $groupname
Write-host "User added:" $user.SiteURL $groupname $user.UserEmailAddress
}

The input namely UserEmailAddress, SiteURL and Group are fetched from a csv file.

This script works fine if the group name is a single word without any space like Approvers, SiteOwners but if the group name has 2 or more words with spaces between them, the script displays the error "Group cannot be found"

I understood the issue and tried different approaches to fix it but nothing works.

| improve this question | | | | |
  • Have you tried wrapping $groupname in quotation marks? -Group "$groupname" – Rune Sperre Mar 27 at 11:46
  • @RuneSperre yes, if i wrap $groupname within quotes, it is considering $groupname as text and not variable. Anything within the quotes is takes a plain text – George Mar 27 at 11:51
  • Do you have this issue for all groups with multiple words name ? – a1mery Mar 27 at 11:56
  • No, variables are expanded inside strings. If you wanted to use $user.group directly you would have to type it as "$($user.group)" though. Reference – Rune Sperre Mar 27 at 11:57
  • @a1mery yes, i face same issue for any group with multiple words – George Mar 27 at 11:57
2

Thanks @RuneSperre for your solution. It worked. Below is the working script

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$users= "" 
$users = import-csv D:\User.csv
foreach ($user in $users)
{
  Add-SPOUser -Site $user.SiteURL -LoginName $user.UserEmailAddress -Group "$($user.group)"
  Write-host "User added:" $user.SiteURL $groupname $user.UserEmailAddress
}
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.