SharePoint Online: Grant Permission to All Files in a Folder using PowerShell

Requirement: Grant Permission to All Files in a Folder in SharePoint Online

PowerShell to Set Permission to each File in a Folder:
#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"
 
#To call non-generic method Load(list, x => x.HasUniqueRoleAssignments)
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))
}
 
Function Grant-ListItemPermission
{
    param
    (   
        [Parameter(Mandatory=$true)] [string]$ItemID
    )
    Try {       
        #Get the List and Item
        $List = $Ctx.Web.Lists.GetByTitle($ListName)
        $ListItem=$List.GetItemByID($ItemID)
        $Ctx.Load($List)
        $Ctx.Load($ListItem)
        $Ctx.ExecuteQuery()
 
        #Check if Item has unique permission already
        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 User
        $User = $Ctx.Web.EnsureUser($UserID)
        $Ctx.load($User)
        $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 -f Green "Permission granted to List Item successfully!"
    }
    Catch {
        Write-host -f Red "Error granting permission to List Item!" $_.Exception.Message
    }
}

Function Get-AllFilesFromFolder
{
    param
    (   
        [Parameter(Mandatory=$true)] [string]$FolderRelativeURL
    )
   Try {     
        #Get the Folder and Files
        $Folder=$Ctx.Web.GetFolderByServerRelativeUrl($FolderRelativeURL)
        $Ctx.Load($Folder)
        $Ctx.Load($Folder.Folders)
        $Ctx.Load($Folder.Files)
        $Ctx.ExecuteQuery()
 
        #Iterate through each File in the folder
        Foreach($File in $Folder.Files)
        {
            #Get Name for each File
            Write-Host ("Granting '{0}' Permission to User {1} on {2} at {3}" -f $PermissionLevel, $UserID, $File.Name, $File.ServerRelativeUrl)
            
            #Get the Properties of the File
            $Ctx.Load($File.ListItemAllFields)
            $Ctx.ExecuteQuery()
 
            #Call the function to grant permission to file
            Grant-ListItemPermission -ItemID $File.ListItemAllFields.Id
        }
        #Recursively process sub-folders
        ForEach($SubFolder in $Folder.Folders | Where{($_.Name -ne "Forms") -and (-Not($_.Name.StartsWith("_")))})
        {
           Get-AllFilesFromFolder $SubFolder.ServerRelativeUrl
        }
    }
    Catch {
        write-host -f Red "Error Getting Files from Folder!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com/Sites/Marketing"
$ListName = "Documents"
$FolderRelativeURL = "/Sites/Marketing/Shared Documents"
$UserID="salaudeen@crescent.com"
$PermissionLevel="Edit"

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

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

#Call the function to process all files in a folder
Get-AllFilesFromFolder -FolderRelativeURL $FolderRelativeURL

PnP PowerShell to Grant Permission to All Files in a Folder in SharePoint Online:
#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$ListName="Documents"
$ParentFolderURL = "/Shared Documents/2018" #Site Relative Path of the document Library
$UserAccount = "Salaudeen@crescent.com"
$Role = "Edit"
 
#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get all Files from the Folder
$AllFiles = Get-PnPFolderItem -ItemType File -FolderSiteRelativeUrl $ParentFolderURL

#Iterate through each File in the Folder
ForEach($File in $AllFiles)
{
    #Grant permissions to the File
    Set-PnPListItemPermission -List $ListName -Identity $File.ListItemAllFields-User $UserAccount -AddRole $Role
    Write-host ("Granted Permission to '{0}' at {1} " -f $File.Name,$File.ServerRelativeUrl)
}
SharePoint Online: Grant Permission to All Files in a Folder using PowerShell SharePoint Online: Grant Permission to All Files in a Folder using PowerShell Reviewed by Salaudeen Rajack on January 06, 2019 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.