SharePoint Online: Get Document Library Permissions and Export to CSV using PnP PowerShell
Requirement: SharePoint Online PowerShell to Get Document Library Permissions.
How to Get SharePoint Online Document Library Permissions?
Are you looking for a way to export permissions on your SharePoint Online document library so that you’ll be sure who has access to your SharePoint Online document library? Or perhaps you want to generate a report of all users with permissions to a specific document library in your SharePoint Online site. Either way, This article will show you how to get document library permissions in SharePoint Online.
- Sign in to the SharePoint Online site with site owner permission and navigate to the document library you want to view permissions from.
- Click on the settings gear in the top-right corner of the screen, then click Library Settings. This will open a library settings page. Click on the “Document Library Permissions” link.
- This will present a page with all users and groups and their permissions assigned to them.
PnP PowerShell to Export Document Library Permissions in SharePoint Online
To export document library permissions in SharePoint Online using PnP PowerShell, get all the List.RoleAssignments property value and then export them using the Export-Csv cmdlet. This PowerShell script exports all permissions of a SharePoint Online document library:
# Parameters
$SiteUrl = "https://crescent.sharepoint.com/sites/ICDocuments"
$ReportOutput = "C:\Temp\LibraryPermissions.csv"
$LibraryName = "IC Documents"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteUrl -Interactive # -Credentials (Get-Credential)
# Get the document library
$Library = Get-PnpList -Identity $LibraryName -Includes RoleAssignments
# Get all users and groups who has access
$RoleAssignments = $Library.RoleAssignments
$PermissionCollection = @()
Foreach ($RoleAssignment in $RoleAssignments)
{
#Get the Permission Levels assigned and Member
Get-PnPProperty -ClientObject $roleAssignment -Property RoleDefinitionBindings, Member
#Get the Principal Type: User, SP Group, AD Group
$PermissionType = $RoleAssignment.Member.PrincipalType
$PermissionLevels = $RoleAssignment.RoleDefinitionBindings | Select -ExpandProperty Name
#Get all permission levels assigned (Excluding:Limited Access)
$PermissionLevels = ($PermissionLevels | Where { $_ -ne "Limited Access"}) -join ","
If($PermissionLevels.Length -eq 0) {Continue}
#Get SharePoint group members
If($PermissionType -eq "SharePointGroup")
{
#Get Group Members
$GroupMembers = Get-PnPGroupMember -Identity $RoleAssignment.Member.LoginName
#Leave Empty Groups
If($GroupMembers.count -eq 0){Continue}
ForEach($User in $GroupMembers)
{
#Add the Data to Object
$Permissions = New-Object PSObject
$Permissions | Add-Member NoteProperty User($User.Title)
$Permissions | Add-Member NoteProperty Type($PermissionType)
$Permissions | Add-Member NoteProperty Permissions($PermissionLevels)
$Permissions | Add-Member NoteProperty GrantedThrough("SharePoint Group: $($RoleAssignment.Member.LoginName)")
$PermissionCollection += $Permissions
}
}
Else
{
#Add the Data to Object
$Permissions = New-Object PSObject
$Permissions | Add-Member NoteProperty User($RoleAssignment.Member.Title)
$Permissions | Add-Member NoteProperty Type($PermissionType)
$Permissions | Add-Member NoteProperty Permissions($PermissionLevels)
$Permissions | Add-Member NoteProperty GrantedThrough("Direct Permissions")
$PermissionCollection += $Permissions
}
}
#Export Permissions to CSV File
$PermissionCollection
$PermissionCollection | Export-CSV $ReportOutput -NoTypeInformation
Write-host -f Green "Permission Report Generated Successfully!"
SharePoint Online PowerShell to Get List Permissions
This PowerShell script can also be used to get list permissions in SharePoint Online. While this script extracts permissions applied on the List, what if you want to get permissions on all underlying objects of the list or library, such as Folders and Files/List items?
#Function to Get Permissions on a particular on List, Folder or List Item
Function Get-PnPPermissions([Microsoft.SharePoint.Client.SecurableObject]$Object)
{
#Determine the type of the object
Switch($Object.TypedObject.ToString())
{
"Microsoft.SharePoint.Client.ListItem"
{
If($Object.FileSystemObjectType -eq "Folder")
{
$ObjectType = "Folder"
#Get the URL of the Folder
$Folder = Get-PnPProperty -ClientObject $Object -Property Folder
$ObjectTitle = $Object.Folder.Name
$ObjectURL = $("{0}{1}" -f $Web.Url.Replace($Web.ServerRelativeUrl,''),$Object.Folder.ServerRelativeUrl)
}
Else #File or List Item
{
#Get the URL of the Object
Get-PnPProperty -ClientObject $Object -Property File, ParentList
If($Object.File.Name -ne $Null)
{
$ObjectType = "File"
$ObjectTitle = $Object.File.Name
$ObjectURL = $("{0}{1}" -f $Web.Url.Replace($Web.ServerRelativeUrl,''),$Object.File.ServerRelativeUrl)
}
else
{
$ObjectType = "List Item"
$ObjectTitle = $Object["Title"]
#Get the URL of the List Item
$DefaultDisplayFormUrl = Get-PnPProperty -ClientObject $Object.ParentList -Property DefaultDisplayFormUrl
$ObjectURL = $("{0}{1}?ID={2}" -f $Web.Url.Replace($Web.ServerRelativeUrl,''), $DefaultDisplayFormUrl,$Object.ID)
}
}
}
Default
{
$ObjectType = "List or Library"
$ObjectTitle = $Object.Title
#Get the URL of the List or Library
$RootFolder = Get-PnPProperty -ClientObject $Object -Property RootFolder
$ObjectURL = $("{0}{1}" -f $Web.Url.Replace($Web.ServerRelativeUrl,''), $RootFolder.ServerRelativeUrl)
}
}
#Get permissions assigned to the object
Get-PnPProperty -ClientObject $Object -Property HasUniqueRoleAssignments, RoleAssignments
#Check if Object has unique permissions
$HasUniquePermissions = $Object.HasUniqueRoleAssignments
#Loop through each permission assigned and extract details
$PermissionCollection = @()
Foreach($RoleAssignment in $Object.RoleAssignments)
{
#Get the Permission Levels assigned and Member
Get-PnPProperty -ClientObject $RoleAssignment -Property RoleDefinitionBindings, Member
#Get the Principal Type: User, SP Group, AD Group
$PermissionType = $RoleAssignment.Member.PrincipalType
#Get the Permission Levels assigned
$PermissionLevels = $RoleAssignment.RoleDefinitionBindings | Select -ExpandProperty Name
#Remove Limited Access
$PermissionLevels = ($PermissionLevels | Where { $_ -ne "Limited Access"}) -join ","
#Leave Principals with no Permissions
If($PermissionLevels.Length -eq 0) {Continue}
#Get SharePoint group members
If($PermissionType -eq "SharePointGroup")
{
#Get Group Members
$GroupMembers = Get-PnPGroupMember -Identity $RoleAssignment.Member.LoginName
#Leave Empty Groups
If($GroupMembers.count -eq 0){Continue}
$GroupUsers = ($GroupMembers | Select -ExpandProperty Title) -join "; "
#Add the Data to Object
$Permissions = New-Object PSObject
$Permissions | Add-Member NoteProperty Object($ObjectType)
$Permissions | Add-Member NoteProperty Title($ObjectTitle)
$Permissions | Add-Member NoteProperty URL($ObjectURL)
$Permissions | Add-Member NoteProperty HasUniquePermissions($HasUniquePermissions)
$Permissions | Add-Member NoteProperty Users($GroupUsers)
$Permissions | Add-Member NoteProperty Email($RoleAssignment.Member.Email)
$Permissions | Add-Member NoteProperty Type($PermissionType)
$Permissions | Add-Member NoteProperty Permissions($PermissionLevels)
$Permissions | Add-Member NoteProperty GrantedThrough("SharePoint Group: $($RoleAssignment.Member.LoginName)")
$PermissionCollection += $Permissions
}
Else
{
#Add the Data to Object
$Permissions = New-Object PSObject
$Permissions | Add-Member NoteProperty Object($ObjectType)
$Permissions | Add-Member NoteProperty Title($ObjectTitle)
$Permissions | Add-Member NoteProperty URL($ObjectURL)
$Permissions | Add-Member NoteProperty HasUniquePermissions($HasUniquePermissions)
$Permissions | Add-Member NoteProperty Users($RoleAssignment.Member.Title)
$Permissions | Add-Member NoteProperty Email($RoleAssignment.Member.Email)
$Permissions | Add-Member NoteProperty Type($PermissionType)
$Permissions | Add-Member NoteProperty Permissions($PermissionLevels)
$Permissions | Add-Member NoteProperty GrantedThrough("Direct Permissions")
$PermissionCollection += $Permissions
}
}
#Export Permissions to CSV File
$PermissionCollection | Export-CSV $ReportFile -NoTypeInformation -Append
}
#Function to get sharepoint online list permissions report
Function Generate-PnPListPermissionRpt()
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$false)] [String] $SiteURL,
[Parameter(Mandatory=$false)] [String] $ListName,
[Parameter(Mandatory=$false)] [String] $ReportFile,
[Parameter(Mandatory=$false)] [switch] $ScanItemLevel,
[Parameter(Mandatory=$false)] [switch] $IncludeInheritedPermissions
)
Try {
#Function to Get Permissions of All List Items of a given List
Function Get-PnPListItemsPermission([Microsoft.SharePoint.Client.List]$List)
{
Write-host -f Yellow "`t `t Getting Permissions of List Items in the List:"$List.Title
#Get All Items from List in batches
$ListItems = Get-PnPListItem -List $List -PageSize 500
$ItemCounter = 0
#Loop through each List item
ForEach($ListItem in $ListItems)
{
#Get Objects with Unique Permissions or Inherited Permissions based on 'IncludeInheritedPermissions' switch
If($IncludeInheritedPermissions)
{
Get-PnPPermissions -Object $ListItem
}
Else
{
#Check if List Item has unique permissions
$HasUniquePermissions = Get-PnPProperty -ClientObject $ListItem -Property HasUniqueRoleAssignments
If($HasUniquePermissions -eq $True)
{
#Call the function to generate Permission report
Get-PnPPermissions -Object $ListItem
}
}
$ItemCounter++
Write-Progress -PercentComplete ($ItemCounter / ($List.ItemCount) * 100) -Activity "Processing Items $ItemCounter of $($List.ItemCount)" -Status "Searching Unique Permissions in List Items of '$($List.Title)'"
}
}
#Get the List
$List = Get-PnpList -Identity $ListName -Includes RoleAssignments
Write-host -f Yellow "Getting Permissions of the List '$ListName'..."
#Get List Permissions
Get-PnPPermissions -Object $List
#Get Item Level Permissions if 'ScanItemLevel' switch present
If($ScanItemLevel)
{
#Get List Items Permissions
Get-PnPListItemsPermission -List $List
}
Write-host -f Green "`t List Permission Report Generated Successfully!"
}
Catch {
write-host -f Red "Error Generating List Permission Report!" $_.Exception.Message
}
}
#region ***Parameters***
$SiteURL="https://crescent.sharepoint.com/sites/marketing"
$ListName = "Branding"
$ReportFile="C:\Temp\ListPermissionRpt.csv"
#endregion
#Remove the Output report if exists
If (Test-Path $ReportFile) { Remove-Item $ReportFile }
#Connect to the Site
Connect-PnPOnline -URL $SiteURL -Credentials (Get-Credential)
#Get the Web
$Web = Get-PnPWeb
#Call the function to generate list permission report
Generate-PnPListPermissionRpt -SiteURL $SiteURL -ListName $ListName -ReportFile $ReportFile -ScanItemLevel
#Generate-PnPListPermissionRpt -SiteURL $SiteURL -ListName $ListName -ReportFile $ReportFile -ScanItemLevel -IncludeInheritedPermissions
Here is the SharePoint Online document library permission report generated by the PowerShell:
How about developing a permission report for all document libraries on a site? Just call the function Generate-PnPListPermissionRpt for all libraries! Here is how:
#region ***Parameters***
$SiteURL="https://crescent.sharepoint.com/sites/marketing"
$ReportsPath="C:\Temp\"
#endregion
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
#Get the Web
$Web = Get-PnPWeb
#Get all document libraries - Exclude Hidden Libraries
$DocumentLibraries = Get-PnPList | Where-Object {$_.BaseType -eq "DocumentLibrary" -and $_.Hidden -eq $false}
ForEach($Library in $DocumentLibraries)
{
#Remove the Output report if exists
$ReportFile = [string]::Concat($ReportsPath, $Library.title,".csv")
If (Test-Path $ReportFile) { Remove-Item $ReportFile }
#Call the function to generate list permission report
Generate-PnPListPermissionRpt -SiteURL $SiteURL -ListName $Library.Title -ReportFile $ReportFile
}
Wrapping up
In conclusion, using PnP PowerShell to retrieve and export document library permissions to a CSV file is a useful and efficient way to manage SharePoint Online sites. By following the steps outlined in this article, you can quickly and easily retrieve the permissions for a document library and export them to a CSV file for further analysis or management. This can help organizations keep track of who has access to specific resources, and can also be used to identify potential security risks and ensure that only authorized users have access to sensitive information. By utilizing PnP PowerShell, you can simplify the process of managing document library permissions in SharePoint Online and help ensure that your organization’s data remains secure.
If you want to create a permission report for all content on a site, use: SharePoint Online Site Permissions Report using PowerShell
Excellent Script, especially the second one. One wee issue i hope you can help with. When it successfully extracts the Library permissions and writes the file to the temp folder, all the files have no extension. Ie no “.csv” tried to see if i could amend the script but failed so far. Any help appreciated.
G
Fixed it! Thanks.
I get error:
Error Generating List Permission Report! Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
I have 300k items in the library. Is it possible to use Graph API for similar Reports but more reliable?
Of course, Yes! Graph APIs are far better. Instead of direct-user login/saved credentials, Try with Azure App ID!
Second script errors out for me, “Error Generating List Permission Report! You cannot call a method on a null-valued expression.”
I believe it’s because the $object variable is never declared? I can’t see any other variable without an obvious declaration.
Hello Team,
The script is working good. Just a slight change i need on this is to make this same script with user specific.I can see on the report is all the users are mentioned for a particular folder. I want it to be an individual user .How can i do that. Once the script generate report for user1 then it should make an entry for user2,user3 and so on.How can i do that. I can see your folder access report for sharepoint .But on that script i have to mention the folder path for manually . Is there a way to make once run and get the folder permissions user specific at once.
I have this issue:
“The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.”
How to resolve it, please ?
Is there a way to export library permissions without using Powershell? Maybe by using the ODataFeed?
The script works great to get the permissions on the Document Library and sub-folders. For some of the sub-folders, we have used Azure AD Security Groups to grant Direct Permissions. How can I get the names of the AAD Security Groups in the report?
Add an “Elseif” part: ElseIf($PermissionType -eq “SecurityGroup”) { #Extract Group Details}
Everything works fine until I use -ScanItemLevel -IncludeInheritedPermissions, then I get the “The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested” error. My list has 1.3 million items. It will stop at about 2400 items.
Thanks!
Hell, this script is very useful and runs fine until I run with -IncludeInheritedPermissions. The script gets through about 2400 items, then throws “The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested”. The list I have to iterate through has 1.3 million items. Like I said, the other two commands work fine, it’s just when I try to include inherited permissions. Thanks!
Is it possible to get the permissions of all folders / files of a document library (or all libraries) but with the groups expanded to include the users?
excellent, thank you!
Hi,
I am getting below error. Could you please help for this error. Thank you.
Error:
Error Generating List Permission Report! Cannot process argument transformation on parameter ‘Object’. Cannot convert the “Microsoft.SharePoint.Client.List” value of type “Microsoft.SharePoint.Client.List” to type “Microsoft.SharePoint.Client.SecurableObject”.
Thanks,
Raja.
Ah, thank you for pointing that out, I have followed your directions to remove what I had and install the newer version, running it now. Thanks!
FYI, I kept getting this error: Error Generating List Permission Report! The term ‘Get-PnPGroupMember’ I finally figured out the correct cmdlet is actually Get-PnPGroupMembers . Note the “s”. I also used Connect-PnPOnline -URL $SiteURL -SPOManagementShell with better success than the other login methods.
Well, this is because you are running the older version of PnP PowerShell! How to Install the PnP PowerShell Module for SharePoint Online?
Is it possible to identify shared items depending on how they have been shared? Ej: users who have the link,
Specific persons, etc
Hi, For me was working ok for the first two sites, and then it’s showing the same (default) libraries for all others sites.
It looks like it’s showing cached list of libraries.
same for me…the problem is the “-” symbol…delete it and type again
Had exactly this issue, closed ISE and re-opened. Then redefined both functions as above (Get-PnPPermissions and then Generate-PnPListPermissionRpt) – now works fine!
Hi, This failed for me with:
Unexpected token ‘–ne “Limited’ in expression or statement.
because it didn’t like the line trying to filter limited access (this one)
$PermissionLevels = ($PermissionLevels | Where { $_ -ne “Limited Access”}) -join “,”
I got around this by changing this line
$PermissionLevels = $RoleAssignment.RoleDefinitionBindings | Select -ExpandProperty Name
to filter out the limited access
$PermissionLevels = $RoleAssignment.RoleDefinitionBindings |?{$_.Name -ne “Limited Access”}| Select -ExpandProperty Name
and then removing the offending line completely, I hope that helps someone else 😎
hello, i might be in right page here since i’m looking for ways to export the list of users that has access to Document Libraries in one of our SharePoint Online site. may i know please and will really appreciate if you can guide me to achieve these:
1. how to connect to SharePoint Online with MFA enabled security
2. how to export to Excel all the permission of every document library in our Site?
thanks upfront for your time 😉
1. Use this article for How to Connect to SharePoint Online from PowerShell using MFA Enabled Account?
2. Just call the function Generate-PnPListPermissionRpt for all libraries! Article has been appended!
Thanks for your time looking at it, I saved as .ps1 your recent added section here “Generate-PnPListPermissionRpt” and run but I am prompted by username and password. Normally we used to login with MFA.
Instead of “Connect-PnPOnline -URL $SiteURL -Credentials (Get-Credential)”, use: Connect-PnPOnline -URL $SiteURL -Interactive to login with MFA enabled accounts.
@Salaudeen, thank you for a lot of patience to me, when I run the script after using “-Interactive”, I got below error message
PS C:UsersmynameDocumentsPowerShellVN> .DocLibrary.ps1 Generate-PnPListPermissionRpt : The term ‘Generate-PnPListPermissionRpt’ is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.
At C:UsersmynameDocumentsPowerShellVNDocLibrary.ps1:22 char:5
+ Generate-PnPListPermissionRpt -SiteURL $SiteURL -ListName $Librar …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Generate-PnPListPermissionRpt:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Hello, thank you so much for all the scripts that you provide. It helps people like me who are facing trouble with the Powershell Script pnp.
However, I also get the same error, that this cmdlet is not recognized. Is there any way I can get rid of this ??
Please help
Hi Thank you for the Script, But i am getting this error: Error Generating List Permission Report! Cannot process argument transformation on parameter ‘Object’. Cannot convert the “Microsoft.SharePoint.Client.List” value of type “Microsoft.SharePoint.Client.List” to type “Microsoft.SharePoint.Client.SecurableObject”.
Any help?
Did you ever figure this out?
I had to start a new PS session and new PS window to get past the “Cannot convert the error: “Microsoft.SharePoint.Client.List” value of type “Microsoft.SharePoint.Client.List” to type “Microsoft.SharePoint.Client.SecurableObject”
Try closing the PowerShell ISE and Opening it again!
Is there a script that applies these csv permissions?
If you’re not getting any errors, you may want to try uncommenting one of the other two function calls at the bottom.
Thanks to the author for an awesome script! Very useful!
With your second script I am only retrieving the permissions of the docLib and not of any subfolders/files. I am not sure what’s wrong with the script, I have changed the parameters. Anyone else having the same problem?
If you’re not getting any errors, you may want to try uncommenting one of the other two function calls at the bottom.
(Sorry, below comment was meant to be a reply).