SharePoint Online: How to Create a Group using PowerShell?

Requirement: Create a new group in SharePoint Online using PowerShell.

A SharePoint group is a container of users who share a similar set of permissions. SharePoint groups provide a convenient way to manage security as a group centrally rather than managing individual users. We can organize users into groups (up to 5,000) and set permissions to the group at site level and then use it in any underlying objects like subsites, lists and list items.

By default, SharePoint creates three user groups upon site creation: Owners, Members and visitors and you need to be a site owner/site collection admin to grant permissions to the group. So, how to create a user group in SharePoint Online?

How to Create a Group in SharePoint Online?
SharePoint Online groups can be created to meet custom security requirements. Here is how to create SharePoint Online group:
  • Navigate to your SharePoint online site, Click on Site Settings gear icon and then select Site Settings >> From the Site settings page, click Site Permissions in the Users And Permissions section.
  • From the Permissions page, click on Create Group icon from the ribbon, under Permissions tab.
    SharePoint Online PowerShell to create group
  • On Create Group page, provide the Name, optionally other settings such as description, owner to the group. Set group settings like who can view/edit group membership, Allow users to request membership, leave the group. All requests will be sent to the specified E-mail.
  • Specify the Group Owner. By default, its set as the user who creates the SharePoint group. 
  • In the "Give group permission to this site" section, select the appropriate check box to assign the permission level to your new group.
    SharePoint online Create Group using PowerShell
  • Click Create.
Once the group is created, you can rename it, change permissions of the group in one place, and add/remove people to it. Let's see the PowerShell for SharePoint online to create group.

Create Group in SharePoint Online using PowerShell
The New-SPOSiteGroup PowerShell cmdlet lets you create a new SharePoint group in SharePoint Online site collection. This cmdlet requires the site collection's URL where you wish to create this new SharePoint group, name of the new group, and the permission level(s) that you wish to assign to it. The below PowerShell script shows how you can use this cmdlet to create a new security group "Marketing Staff" in your SharePoint Online site called Marketing with both Edit and Design rights.

Here is an example of creating a new user group in SharePoint Online using PowerShell
#Variables for Admin Center & Site Collection URL
$AdminCenterURL = "https://crescent-admin.sharepoint.com/"
$SiteCollectionURL = "https://crescent.sharepoint.com/sites/marketing"

#Connect to SharePoint Online
Connect-SPOService -url $AdminCenterURL -Credential (Get-Credential)

#sharepoint online powershell add group to site
New-SPOSiteGroup -Site $SiteCollectionURL -Group "Marketing Staff" -PermissionLevels "Design", "Edit"
This cmdlet creates a new group in the SharePoint Online site collection.

SharePoint Online PowerShell to Add Group to Site
Let's create a new user group in SharePoint Online using PowerShell CSOM.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
#Variables for Processing
$SiteURL = "https://Crescent.sharepoint.com/Sites/Sales"
$GroupName="Sales Managers90"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Cred

#sharepoint online create group powershell
$GroupInfo = New-Object Microsoft.SharePoint.Client.GroupCreationInformation
$GroupInfo.Title = $GroupName      
$Group = $Ctx.web.SiteGroups.Add($GroupInfo)
$Ctx.ExecuteQuery()
Plain and simple, huh.. Let's add some error handling code and assign permissions to the created group.

SharePoint Online Create Group using PowerShell
Here is the PowerShell CSOM script to create SharePoint group.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
#Variables for Processing
$SiteURL = "https://crescent.sharepoint.com/Sites/Sales"
$GroupName="Sales Managers"
$PermissionLevel="Edit"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred

    #Get all existing groups of the site
    $Groups = $Ctx.Web.SiteGroups
    $Ctx.load($Groups)
    $Ctx.ExecuteQuery()
    
    #Get Group Names
    $GroupNames =  $Groups | Select -ExpandProperty Title
    
    #Check if the given group doesn't exist already
    If($GroupNames -notcontains $GroupName)
    {
        #sharepoint online powershell create group
        $GroupInfo = New-Object Microsoft.SharePoint.Client.GroupCreationInformation
        $GroupInfo.Title = $GroupName      
        $Group = $Ctx.web.SiteGroups.Add($GroupInfo)
        $Ctx.ExecuteQuery()

        #Assign permission to the group
        $RoleDef = $Ctx.web.RoleDefinitions.GetByName($PermissionLevel)
        $RoleDefBind = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
        $RoleDefBind.Add($RoleDef)
        $Ctx.Load($Ctx.Web.RoleAssignments.Add($Group,$RoleDefBind))
        $Ctx.ExecuteQuery()

        write-host  -f Green "User Group has been Added Successfully!"
    }
    else
    {
        Write-host -f Yellow "Group Exists already!"
    }
}
Catch {
    write-host -f Red "Error Creating New user Group!" $_.Exception.Message
}
This script creates new SharePoint Online group and assigns permission to the group.

Create SharePoint Online Groups using PnP PowerShell
Here is the SharePoint Online PnP PowerShell to add group to site.
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$GroupName ="Contributors"
$Permissions="Contribute"

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Connect to PNP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred
    
    #Create a new group in SharePoint Online
    $Group = New-PnPGroup -Title $GroupName -ErrorAction Stop

    #Set Group Permissions
    Set-PnPGroupPermissions -Identity $Group -AddRole $Permissions    
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
This PowerShell adds group to SharePoint Online site.

PnP PowerShell to Create Multiple Groups from a CSV File
This time, let's use a CSV file to bulk create SharePoint Online Groups.
#Function to Create SharePoint Online Group
Function Add-PnPGroup($SiteURL, $GroupName, $Permission)
{
    Try {
        #Connect to SharePoint Online Site
        Connect-PnPOnline -url $SiteURL -UseWebLogin
        $Web = Get-PnPWeb

        Write-host "Creating Group '$GroupName'..." -f Yellow -NoNewline
        #Check if the group exists already
        If((Get-PnPGroup | Where { $_.Title -eq $GroupName}) -eq $Null)
        {
            #Create SharePoint Online Group
            $Group = New-PnPGroup -Title $GroupName -ErrorAction Stop
 
            #Set Group Permissions on the Web
            Set-PnPGroupPermissions -Identity $GroupName -AddRole $Permission -Web $Web
            Write-host "Done!" -f Green
        }
        Else
        {
            Write-host "Group '$GroupName' already exists!" -f Yellow
        }
    }
    Catch {
        Write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
    }
}

#Parameters
$CSVFile = "C:\Temp\Groups.csv"

#Get Groups Data from CSV
$GroupData = Import-Csv -Path $CSVFile | ForEach-Object {
        #Call function to Create Group
        Add-PnPGroup -SiteURL $_.SiteURL -GroupName $_.GroupName -Permission $_.Permission
}
Here is my CSV File: Bulk Create SharePoint Online Groups from a CSV File.

1 comment:

  1. Thanks for this article saved me a lot of time an effort

    ReplyDelete

Please Login and comment to get your questions answered!

Powered by Blogger.