I wrote a script in Powershell to reset the role inheritance of multiple files in a Sharepoint document library.
Worked fine until I ran across a library with more than 5000 files. Found a solution for this and kept going.
The script works fine but every now and then it throws a random error and I have to start over. This is fine as long as there isn't that many files, I can just run it again.
Now, I have a library with 1.3M files (I know...). The chance of crashing while going through this is almost 100% and restarting it will take way to long. So, I figured I would run thru one folder at a time instead which would bring down the number of files per run. Doing this introduces the threshold of 5000 files again though, any idea on how to bypass this when going through a folder at a time?
$url = 'https://domain.sharepoint.com/'
$ListTitle = 'List Name'
$folderName = 'Folder Name'
# Paths to SDK. Please verify location on your computer.
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"
# Login
$ctx=New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$username = "[email protected]"
$AdminPassword = "my password"
$password = ConvertTo-SecureString -string $AdminPassword -AsPlainText -Force
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
# Fetch list
$ll=$ctx.Web.Lists.GetByTitle($ListTitle)
$ctx.Load($ll)
$ctx.ExecuteQuery()
# Find folder
$folder = $ctx.Web.GetFolderByServerRelativeUrl($ctx.Web.ServerRelativeUrl + $listTitle + '/' + $folderName + '/')
$ctx.Load($folder)
$ctx.ExecuteQuery();
# Fetch items
$spQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
## View XML
$qCommand = @"
<View Scope="RecursiveAll">
<Query>
<OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
</Query>
<RowLimit Paged="TRUE">5000</RowLimit>
</View>
"@
## Page Position
$position = $null
## All Items
$allItems = @()
Do
{
$spQuery.ListItemCollectionPosition = $position
$spQuery.ViewXml = $qCommand
## Executing the query
$spQuery.FolderServerRelativeUrl = $folder.ServerRelativeUrl
$itemki = $ll.GetItems($spQuery)
$ctx.Load($itemki)
$ctx.ExecuteQuery()
# Loop through all items
$noOfObject = $itemki.Count
for($j=0;$j -lt $itemki.Count ;$j++)
{
$itemki[$j].ResetRoleInheritance()
if($j % 500 -eq 0) # Processing 500 items at a time.
{
$ctx.ExecuteQuery()
}
}
$ctx.ExecuteQuery()
## Getting the position of the previous page
$position = $itemki.ListItemCollectionPosition
Write-Host $position.PagingInfo $position.TypeId
# Adding current collection to the allItems collection
$allItems += $itemki
}
# the position of the last page will be Null
Until($position -eq $null)