SharePoint Online: PowerShell to Grant Site Permissions to User

Requirement: Grant permissions to SharePoint Online site using PowerShell

SharePoint Online: PowerShell to Set Site Permissions
In SharePoint Online modern sites, the default granularity options for accessing SharePoint content are as follows:
  • Full Control, which is granted to Owners
  • Edit, which is granted to Members
  • Read, which is granted to Visitors (guests).
The below PowerShell script adds users to the site with "Contribute" permissions directly.
#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 = ""
$UserAccount = "[email protected]"
$PermissionLevel = "Contribute"

#Setup Credentials to connect
$Cred = Get-Credential

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
    #Get the Web
    $Web = $Ctx.Web

    #Ensure the user

    #Get the Permission Level  
    $RoleDefinition = $web.RoleDefinitions.GetByName($PermissionLevel) 
    $RoleAssignment = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
    #Assign Role Assignment to User
    $Permissions = $Web.RoleAssignments.Add($User,$RoleAssignment) 
    Write-host  -f Green "User '$UserAccount' has been Granted with Access '$PermissionLevel'!"
Catch {
    write-host -f Red "Error:" $_.Exception.Message

PnP PowerShell to Grant Permission to User
We can provide permissions to the site directly without adding users to existing site groups. Here is the PnP PowerShell to add user to a site in SharePoint Online:
$SiteURL = "" 
$UserAccount = "[email protected]"
$PermissionLevel = "Contribute"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin    

#grant access to sharepoint online site with powershell
Set-PnPWebPermission -User $UserAccount -AddRole $PermissionLevel
This PowerShell adds permissions to SharePoint Online site.

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.