← script library

Managing File Permissions in SharePoint with PowerShell

SharePoint & OneDriveJanuary 4, 2025

Today, we will focus on managing file permissions in SharePoint using PowerShell. This script helps administrators efficiently view and configure permissions for files and folders within SharePoint document libraries. By automating the management of file permissions, you can ensure that sensitive information is only accessible to the right users, enhancing your organizations security and compliance posture.

powershell
# Load SharePoint Online module
Import-Module Microsoft.Online.SharePoint.PowerShell -ErrorAction SilentlyContinue
if (-not (Get-Module -Name "Microsoft.Online.SharePoint.PowerShell")) {
    Write-Host "SharePoint Online module not found. Please install it first."
    return
}

# Set the credentials and connect to SharePoint Online
$credential = Get-Credential
Connect-SPOService -Url https://yourtenant-admin.sharepoint.com -Credential $credential
Write-Host "Connected to SharePoint Online successfully."

# Define the SharePoint site and file URL
$siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite"
$fileUrl = "/sites/yoursite/Shared Documents/yourfile.docx"  # Path to your file or folder

# Get current permissions of the file
$permissions = Get-PnPListItem -List "Documents" -Identity $fileUrl | Get-PnPProperty -Property RoleAssignments
foreach ($assignment in $permissions) {
    $principal = $assignment.Member.LoginName
    $roles = $assignment.RoleDefinitionBindings | ForEach-Object { $_.Name }
    Write-Host "User: $principal - Roles: $($roles -join , )"
}

# Add a users permissions
$userToAdd = "[email protected]"  # Change to the user who needs access
$roleToAdd = "Edit"  # Role to assign (e.g., Read, Contribute, Edit)
Add-PnPFilePermission -List "Documents" -Identity $fileUrl -User $userToAdd -AddRole $roleToAdd
Write-Host "Added $userToAdd with $roleToAdd access to $fileUrl."

# Summary of the changes
Write-Host "Permissions have been updated successfully."
Write-Host "Please verify the permissions to ensure that they are set as intended."

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.