Introduction
Using PnP Powershell you can programmatically count files in a folder or the entire library in SharePoint Online that have unique permissions.
Count files with unique permissions in a folder
The following PnP cmdlets count files with unique permissions in a folder.
# Define the folder URL relative to the document library
$folderUrl = "/sites/yoursite/Shared Documents/YourFolder"
$list = "Shared Documents"
# Initialize the count for items with unique permissions
$fileCountWithUniquePermissions = 0;
# Get the folder
$folder = Get-PnPFolder -Url $folderUrl -Includes Files, Folders
foreach ($file in $folder.Files) {
$fileItem = Get-PnPListItem -List $list -Id $file.ListItemAllFields.Id
if ($fileItem.HasUniqueRoleAssignments) {
$fileCountWithUniquePermissions++
}
}
# Output the total count
Write-Host "Total files: $fileCountWithUniquePermissions"
Count files or items with unique permissions in a list
The following lines can help you count files in a document library with unique permissions or items with unique permissions in a list.
# Define the list name
$listName = "YourListName"
# Get all list items
$items = Get-PnPListItem -List $listName -PageSize 5000
# Initialize the count for items with unique permissions
$uniquePermissionCount = 0
# Iterate through each item to check for unique permissions
foreach ($item in $items) {
# Check if the item has unique permissions
if ($item.HasUniqueRoleAssignments) {
# Increment the count if unique permissions are found
$uniquePermissionCount++
}
}
# Output the total count of items with unique permissions
Write-Host "Total items with unique permissions: $uniquePermissionCount"