Automating File and Folder Permissions Checks in SharePoint with PowerShell

Managing file and folder permissions within SharePoint is vital for ensuring that sensitive information is secure while enabling collaboration among users. This PowerShell script automates the process of checking permissions for files and folders within a specified SharePoint document library. With this script, administrators can quickly assess who has access to what and make informed decisions about permission adjustments.
This script will:
1. Connect to a SharePoint site.
2. Retrieve the permissions for a specified document library.
3. Display the permissions set for each file and folder in that library.
By using this script, IT administrators can efficiently manage and audit permissions across their SharePoint environment.

# Install SharePoint Online Management Shell if not already installed
if (-Not (Get-Module -ListAvailable -Name Microsoft.Online.SharePoint.PowerShell)) {
    Install-Module -Name Microsoft.Online.SharePoint.PowerShell -Scope CurrentUser -AllowClobber
}
# Connect to SharePoint Online
$siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite"
$credential = Get-Credential
Connect-SPOService -Url $siteUrl -Credential $credential
# Specify the document library
$libraryName = "Documents"
# Retrieve items from the specified library
$items = Get-SPOSiteGroup -Site $siteUrl | Get-SPOListItem -List $libraryName
Write-Host "=== Permissions for Files and Folders in $libraryName ==="
foreach ($item in $items) {
    $permissions = Get-SPOUser -Identity $item.Id -Site $siteUrl
    Write-Host "Item: $($item.FieldValues["FileLeafRef"])"
    foreach ($permission in $permissions) {
        Write-Host "  User: $($permission.LoginName) - Role: $($permission.Role)"
    }
}
# Disconnect from SharePoint
Disconnect-SPOService
Write-Host "Permissions check completed."