Is there a way to use Add-PnPUserToGroup command to add a AD Security Group into a SharePoint group on SharePoint Online?

I'm writing a script which does some post-some creation tasks and just after a way to do this without writing lines and lines of code. I saw one-liner examples of adding security groups as site collection admins, but haven't found a way to add this to a SP Group.

When I try Add-PnPUserToGroup -LoginName parameter I get an:

Add-PnPUserToGroup : The object is used in the context different from the one associated with the object.

Error so I think I may be doing something daft there!

I would really appreciate help on this.

Thank you


I think you are missing the Connection parameter here you need to pass in the context of site for which you are executing the command which can be obtained by using -ReturnConnection switch

$connection = Connect-PnPOnline -Url https://contoso.sharepoint.com -Credentials (Get-Credential) -ReturnConnection

Add-PnPUserToGroup -LoginName user@company.com -Connection $connection #variable form above line
  • Thank you, will try this now
    – ova
    Sep 4 '20 at 12:57

That cmdlet is used to add to a SharePoint group. To add to an Azure AD group, use Add-AzureADGroupMember. For Active Directory, use Add-ADGroupMember.


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.