How to delete unique permissions on all the documents in the Library using Powershell

seb seb 36 Reputation points
2021-12-30T15:38:22.41+00:00

Hello,

I am looking for a script to remove unique permissions on all documents in a library.

i found the script below but it only removes permissions from folders and subfolders but not files.

Can you please help me?

Thank you,

#Set Variables
$SiteURL = "https://XXXXXX.sharepoint.com/"
$FolderURL = "/XXXX" #Document Library Site Relative URL

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

#Function to reset permissions of all Sub-Folders
Function Reset-SubFolderPermissions($FolderURL)
{
    #Get all sub-folders of the Folder - Exclude system folders
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderURL -ItemType Folder | Where {$_.Name -ne "Forms" -and $_.Name -ne "Document"}

    #Loop through each sub-folder
    ForEach($SubFolder in $SubFolders)
    {
        $SubFolderURL = $FolderUrl+"/"+$SubFolder.Name
        Write-host -ForegroundColor Green "Processing Folder '$($SubFolder.Name)' at $SubFolderURL"

        #Get the Folder Object - with HasUniqueAssignments and ParentList properties
        $Folder = Get-PnPFolder -Url $SubFolderURL -Includes ListItemAllFields.HasUniqueRoleAssignments, ListItemAllFields.ParentList, ListItemAllFields.ID

        #Get the List Item of the Folder
        $FolderItem = $Folder.ListItemAllFields

        #Check if the Folder has unique permissions
        If($FolderItem.HasUniqueRoleAssignments)
        {
            #Reset permission inheritance
            Set-PnPListItemPermission -List $FolderItem.ParentList -Identity $FolderItem.ID -InheritPermissions
            Write-host "`tUnique Permissions are removed from the Folder!"
        }

        #Call the function recursively
        Reset-SubFolderPermissions $SubFolderURL
    }
}

#Call the function
Reset-SubFolderPermissions $FolderURL
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
11,098 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,605 questions
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Lorenzo Morello 1 Reputation point
    2021-12-30T15:43:44.313+00:00

  2. Emily Du-MSFT 49,001 Reputation points Microsoft Vendor
    2021-12-31T02:26:46.86+00:00

    @seb seb

    1.You could try to run below PowerShell to reset unique permissions in a document library (with less than 5000 items).

        #Set Variables  
        $SiteURL = "https://crescent.sharepoint.com/sites/Marketing"  
        $ListName = "Documents"  
    
        #Connect to PnP Online  
        Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)  
    
        #Get all list items in batches  
        $ListItems = Get-PnPListItem -List $ListName -PageSize 500  
    
        #Iterate through each list item  
        ForEach($ListItem in $ListItems)  
        {  
            #Check if the Item has unique permissions  
            $HasUniquePermissions = Get-PnPProperty -ClientObject $ListItem -Property "HasUniqueRoleAssignments"  
            If($HasUniquePermissions)  
            {         
                $Msg = "Deleting Unique Permissions on {0} '{1}' at {2} " -f $ListItem.FileSystemObjectType,$ListItem.FieldValues["FileLeafRef"],$ListItem.FieldValues["FileRef"]  
                Write-host $Msg  
                #Delete unique permissions on the list item  
                Set-PnPListItemPermission -List $ListName -Identity $ListItem.ID -InheritPermissions  
            }  
        }  
    

    2.Here is the PowerShell to reset unique permissions in large document libraries (with more than 5000 items).

    #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"  
    
    #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))  
    }  
    
    ##Variables for Processing  
    $SiteUrl = "https://crescent.sharepoint.com/sites/Marketing"  
    $ListName= "Documents"  
    
    #Get Credentials to connect  
    $Cred= Get-Credential  
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)  
    
    #Set up the context  
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)  
    $Context.Credentials = $Credentials  
    
    #Get the List  
    $List = $Context.web.Lists.GetByTitle($ListName)  
    
    $Query = New-Object Microsoft.SharePoint.Client.CamlQuery  
    $Query.ViewXml = "<View Scope='RecursiveAll'><RowLimit>2000</RowLimit></View>"  
    
    #Batch process list items - to mitigate list threshold issue on larger lists  
    Do {   
        #Get items from the list in batches  
        $ListItems = $List.GetItems($Query)  
        $Context.Load($ListItems)  
        $Context.ExecuteQuery()  
    
        $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition  
    
        #Loop through each List item  
        ForEach($ListItem in $ListItems)  
        {  
            Invoke-LoadMethod -Object $ListItem -PropertyName "HasUniqueRoleAssignments"  
            $Context.ExecuteQuery()  
            if ($ListItem.HasUniqueRoleAssignments -eq $true)  
            {  
                #Reset Permission Inheritance  
                $ListItem.ResetRoleInheritance()  
                Write-host  -ForegroundColor Yellow "Inheritence Restored on Item:" $ListItem.ID  
            }  
        }  
        $Context.ExecuteQuery()  
    } While ($Query.ListItemCollectionPosition -ne $null)  
    
    Write-host "Broken Permissions are Deleted on All Items!" -ForegroundColor Green  
    

    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.


  3. seb seb 36 Reputation points
    2022-01-03T10:21:49.95+00:00

    Hi,

    I think i have this error because there are too many files in the library.
    Is it possible to make a script to remove unique permissions on one folder and his sub-folder inside a library ?

    Thanks,
    seb


  4. Emily Du-MSFT 49,001 Reputation points Microsoft Vendor
    2022-01-05T06:41:27.94+00:00

    @seb seb

    You run below PowerShell to remove unique permissions on one 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"  
        
    #Variables  
    $SiteURL = "https://tenant.sharepoint.com/sites/emilytest"  
    $FolderServerRelativeUrl= "/Sites/emilytest/Shared Documents/2022"  
        
    Try {  
        #Get Credentials to connect  
        $Cred= Get-Credential  
        
        #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 from URL  
        $Web = $Ctx.web  
        $Ctx.Load($Web)  
        $Ctx.executeQuery()  
        
        #Get the Folder object by Server Relative URL  
        $Folder = $Web.GetFolderByServerRelativeUrl($FolderServerRelativeUrl)  
        $Ctx.Load($Folder)  
        $Ctx.ExecuteQuery()  
           
        #Reset Folder Permissions  
        $Folder.ListItemAllFields.ResetRoleInheritance()  
        $Ctx.ExecuteQuery()      
        Write-host -f Green "Folder's Unique Permissions are Removed!"  
    }  
    Catch {  
        write-host -f Red "Error Resetting Folder Permissions!" $_.Exception.Message  
    }  
    

    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 Answers by the question author, which helps users to know the answer solved the author's problem.