PnP PowerShell - Add-PnPGroupMember help

Mattps 5 Reputation points
2024-01-19T15:34:20.1233333+00:00

Hi all,

I have created an Azure runbook (PS 7.2) that creates a SharePoint Online site and customises the page webparts.
I am trying to add a user a site member for the newly created site. Using Add-PnPGroupMember in the runbook doesn't do anything:

$SiteMembersGroup = Get-PnPGroup | ? Title -Like '*Members*' | select title    
foreach($member in $SPSiteMembers)
    {
    $member
    Add-PnPGroupMember -LoginName $member -group $SiteMembersGroup   
}          

When I try to test locally (using PnP-Connect), I get the following:

Connect-PnPOnline -url https://contoso.sharepoint.com/abc -Interactive
Add-PnPGroupMember -LoginName ******@test.com

But I get this:

Add-PnPGroupMember : Exception of type 'System.Management.Automation.PSInvalidOperationException' was thrown.
At line:1 char:1
+ Add-PnPGroupMember -LoginName ******@test.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Add-PnPGroupMember], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,PnP.PowerShell.Commands.Principals.AddGroupMember

Has anyone had any success with adding users to Site groups using PnP PowerShell? Thanks in advance,
Matt

Microsoft 365 and Office | SharePoint | Development
Microsoft 365 and Office | SharePoint | For business | Windows
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Xyza Xue_MSFT 30,241 Reputation points Microsoft External Staff
    2024-01-22T02:37:40.9233333+00:00

    Hi @Mattps ,

    You can add users to a site group using this PnP PowerShell:

    #Config Variables
    $SiteURL = "https://yourdomain.sharepoint.com/sites/xyzax-version1" $GroupName = "group2"
    $UserLoginID = "******@yourdomain.onmicrosoft.com"   #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
     
    #sharepoint online powershell to add user to group
    Add-PnPGroupMember -LoginName $UserLoginID -Identity $GroupName
    
    

    Remember to replace the variable $SiteURL, $GroupName, $UserLoginID with your own.

    My test result, very successful:User's image


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.