convert Office 365 powershell array to string with commas
-
18-12-2020 - |
Question
I am trying to add users to an Office 365 group via powershell as described here -
https://technet.microsoft.com/en-us/library/mt238269(v=exchg.160).aspx
I am able to add single or multiple users using the Add-UnifiedGroupLinks
command however I am sourcing a list of users I want to add in from an Office 365 security group and it brings back the users in an array which the command Add-UnifiedGroupLinks
doesnt seem to like
#add the Office 365 security group group to the O365 group
$groupid = "TestGroup" #Office 365 security Group
$alias = "Office365 Group" #office 365 group
$sg = Get-MsolGroup | where-object { $_.DisplayName -eq "$groupid"} #Get the group
$sgemails = Get-MsolGroupMember -GroupObjectId $sg.ObjectId | Select EmailAddress #Get the email addresses
$sgemails # Show the users
Add-UnifiedGroupLinks –Identity $alias -LinkType Members -links $sgemails # Add the users to the Group
Is there a way to convert this array which comes out like
EmailAddresses
user1@test.com
user2@test.com
user3@test.com
to a a string so it is user1@test.com, user2@test.com, user3@test.com
For reference this is the error when you try to run the powershell script
PS U:\> Add-UnifiedGroupLinks –Identity $alias -LinkType Members -links $sgemails
Cannot process argument transformation on parameter 'Links'.
Cannot convert value "System.Collections.ArrayList" to type "Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter[]".
Error: "Cannot convert value "@{EmailAddress=user1@test.com}" to type "Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter".
Error: "Cannot convert hashtable to an object of the following type: Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter.
Hashtable-to-Object conversion is not supported in restricted language mode or a Data section.""
+ CategoryInfo : InvalidData: (:) [Add-UnifiedGroupLinks], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Add-UnifiedGroupLinks
+ PSComputerName : outlook.office365.com
- You would be able to test the above script by just setting the $groupid to a security group in your Office 365 environment and $alias to a O365 group.
Thanks
Solution
Sounds to me like the $sgemails
is still in an array, which it doesn't know what to do with. Let's try to convert it to a string. Change Line 6 (second to last line) to:
$sgemailString = [string]::Join(",",$sgemails)
Add-UnifiedGroupLinks –Identity $alias -LinkType Members -links $sgemailString # Add the users to the Group