SharePoint Online: Grant Permission to User on All Items in a List using PowerShell

Requirement: Grant Permission to a User on All Items in a SharePoint Online List

PowerShell to Grant Permissions to a User on All Items in a List in SharePoint Online
#Load SharePoint Online 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/marketing"
$ListName= "Migration Documents"
$UserAccount = "i:0#.f|membership|salaudeen@crescent.com"
$PermissionLevel = "Edit"

#To call a non-generic method Load
Function Invoke-LoadMethod() {
    param(
            [Microsoft.SharePoint.Client.ClientObject]$Object = $(throw "Please provide a Client Object"),
            [string]$PropertyName
        ) 
   $ctx = $Object.Context
   $load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load") 
   $type = $Object.GetType()
   $clientLoad = $load.MakeGenericMethod($type)
    
   $Parameter = [System.Linq.Expressions.Expression]::Parameter(($type), $type.Name)
   $Expression = [System.Linq.Expressions.Expression]::Lambda([System.Linq.Expressions.Expression]::Convert([System.Linq.Expressions.Expression]::PropertyOrField($Parameter,$PropertyName),[System.Object] ), $($Parameter))
   $ExpressionArray = [System.Array]::CreateInstance($Expression.GetType(), 1)
   $ExpressionArray.SetValue($Expression, 0)
   $clientLoad.Invoke($ctx,@($Object,$ExpressionArray))
}
 
#Get Credentials to connect
$Cred= Get-Credential
   
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
     
#Get the List
$List = $Ctx.web.Lists.GetByTitle($ListName)
 
#Get the User
$User = $Ctx.Web.EnsureUser($UserAccount) 
$Ctx.Load($User)
$Ctx.ExecuteQuery()
  
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml = "<View Scope='RecursiveAll'><RowLimit>2000</RowLimit></View>"
  
#Batch process list items - to mitigate list threashold issue on larger lists
Do {  
    #Get items from the list in batches
    $ListItems = $List.GetItems($Query)
    $Ctx.Load($ListItems)
    $Ctx.ExecuteQuery()
            
    $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
   
    #Loop through each List item
    ForEach($ListItem in $ListItems)
    {
        #Check if List Item has unique permissions
        Invoke-LoadMethod -Object $ListItem -PropertyName "HasUniqueRoleAssignments"
        $Ctx.ExecuteQuery()
 
        #Break Item's permission Inheritance, if its inheriting permissions from the parent
        if (-not $ListItem.HasUniqueRoleAssignments)
        {
            $ListItem.BreakRoleInheritance($true, $false) #keep the existing permissions: Yes -  Clear listitems permissions: No
            $ctx.ExecuteQuery()
        }

        #Get the role 
        $Role = $Ctx.web.RoleDefinitions.GetByName($PermissionLevel)
        $RoleDB = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
        $RoleDB.Add($Role)
          
        #Assign permissions
        $UserPermissions = $ListItem.RoleAssignments.Add($User,$RoleDB)
        $ListItem.Update()
        $Ctx.ExecuteQuery()
 
        Write-host -ForegroundColor Green ("User Added to List Item Permissions ID {0} at {1}" -f $ListItem.ID,$ListItem["FileRef"])
    }    
} While ($Query.ListItemCollectionPosition -ne $null)

Similarly, You can add a SharePoint Group to All Items as:
#Load SharePoint Online 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/marketing"
$ListName= "Migration Documents"
$GroupName = "Marketing Team Site Owners"
$PermissionLevel = "Full Control"

#To call a non-generic method Load
Function Invoke-LoadMethod() {
    param(
            [Microsoft.SharePoint.Client.ClientObject]$Object = $(throw "Please provide a Client Object"),
            [string]$PropertyName
        ) 
   $ctx = $Object.Context
   $load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load") 
   $type = $Object.GetType()
   $clientLoad = $load.MakeGenericMethod($type)
    
   $Parameter = [System.Linq.Expressions.Expression]::Parameter(($type), $type.Name)
   $Expression = [System.Linq.Expressions.Expression]::Lambda([System.Linq.Expressions.Expression]::Convert([System.Linq.Expressions.Expression]::PropertyOrField($Parameter,$PropertyName),[System.Object] ), $($Parameter))
   $ExpressionArray = [System.Array]::CreateInstance($Expression.GetType(), 1)
   $ExpressionArray.SetValue($Expression, 0)
   $clientLoad.Invoke($ctx,@($Object,$ExpressionArray))
}
 
#Get Credentials to connect
$Cred= Get-Credential
   
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
     
#Get the List
$List = $Ctx.web.Lists.GetByTitle($ListName)

#Get the Group
$Group=$ctx.Web.SiteGroups.GetByName($GroupName)
$ctx.Load($Group)
$ctx.ExecuteQuery()

$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml = "<View Scope='RecursiveAll'><RowLimit>2000</RowLimit></View>"
  
#Batch process list items - to mitigate list threashold issue on larger lists
Do {  
    #Get items from the list in batches
    $ListItems = $List.GetItems($Query)
    $Ctx.Load($ListItems)
    $Ctx.ExecuteQuery()
            
    $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
   
    #Loop through each List item
    ForEach($ListItem in $ListItems)
    {
        #Check if List Item has unique permissions
        Invoke-LoadMethod -Object $ListItem -PropertyName "HasUniqueRoleAssignments"
        $Ctx.ExecuteQuery()
 
        #Break Item's permission Inheritance, if its inheriting permissions from the parent
        if (-not $ListItem.HasUniqueRoleAssignments)
        {
            $ListItem.BreakRoleInheritance($true, $false) #keep the existing permissions: Yes -  Clear listitems permissions: No
            $ctx.ExecuteQuery()
        }

        #Get the role - Permission Level
        $Role = $Ctx.web.RoleDefinitions.GetByName($PermissionLevel)
        $RoleDB = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
        $RoleDB.Add($Role)
          
        #Assign permissions
        $GroupPermissions = $ListItem.RoleAssignments.Add($Group,$RoleDB)
        $ListItem.Update()
        $Ctx.ExecuteQuery()
 
        Write-host -ForegroundColor Green ("Group Added to List Item Permissions ID {0} at {1}" -f $ListItem.ID,$ListItem["FileRef"])
    }    
} While ($Query.ListItemCollectionPosition -ne $null)

PnP PowerShell to Add User to All Items in a SharePoint Online List
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/Marketing"
$ListName ="Projects"
$UserID="Peter@TheCrescentTech.com"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get all list items
$ListItems = Get-PnPListItem -List $ListName
ForEach($ListItem in $ListItems)
{
    #Grant permission on List Item to User
    Set-PnPListItemPermission -Identity $ListItem.ID -List $ListName -AddRole "Edit" -User $UserID
}
SharePoint Online: Grant Permission to User on All Items in a List using PowerShell SharePoint Online: Grant Permission to User on All Items in a List using PowerShell Reviewed by Salaudeen Rajack on January 08, 2019 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.