Script Repository


Change permissions for SharePoint folder

September 25, 2019
1578

This script updates permissions for a SharePoint folder. To use it in Adaxes, you can add the script to a Business Rule, Custom Command or Scheduled Task using the Run a program or PowerShell script action.

Script 1: SharePoint on-premise

Parameters:

  • $sharePointServer - Specifies the NetBIOS name of the computer where the SharePoint Sever is homed.
  • $webApplicationURL - Specifies the URL of the SharePoint web application.
  • $folderPath - Specifies the path to the folder for which to update the access permissions.
    Note: You can use value references (e.g. %name%) to use properties of the object on which the script is executed as a part of the folder path. For example, if you specify Shared Documents/Folder A/%name% and execute the script on a user whose name is John Doe, the resulting path will be Shared Documents/Folder A/John Doe.
  • $stopInheritablePermissions - Specifies whether to stop inheriting permissions from the parent.
  • $securityItems - Specifies the permissions to set.
    You can specify custom security settings for users, Active Directory groups or SharePoint groups. Format:

    "DOMAIN\username"="RoleType";"DOMAIN\groupname"="RoleType";"SharePointGroupName"="RoleType"

    Default role types: Administrator, Contributor, Reader, WebDesigner.
Edit Remove
PowerShell
$sharePointServer = "SharePointServer" # TODO: modify me

$webApplicationURL = "http://$sharePointServer/sites/MySite" # TODO: modify me
$folderPath = "Shared Documents/Folder A/%name%" # TODO: modify me
$stopInheritablePermissions = $True # TODO: modify me. Specify $False to inherits permissions from the parent or $True to stop inheritance

$securityItems = @{"EXAMPLE\Administrator"="Administrator";"SharePointDesigners"="WebDesigner"} # TODO: modify me

# Connect to the SharePoint Server
$session = New-PSSession $sharePointServer -Authentication Kerberos
$result = Invoke-Command -Session $session -ArgumentList $webApplicationURL, $folderPath, $newFolderPath, $stopInheritablePermissions, $securityItems -ScriptBlock {
    param($webApplicationURL, $folderPath, $newFolderPath, $stopInheritablePermissions, $securityItems)
    
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-Null
    
    # Open the web application
    $site = New-Object Microsoft.SharePoint.SPSite("$webApplicationURL")
    $web = $site.OpenWeb();

    # Access the folder
    $folder = $web.GetFolder($folderPath)
    
    if ($folder.Exists)
    {
        $folder = $folder.Item
        if ($stopInheritablePermissions)
        {
            $folder.BreakRoleInheritance($true)
            $userFolderRoleAssignments = $folder.RoleAssignments
            $userFolderRoleAssignmentsCount = $userFolderRoleAssignments.Count
            for ($i = $userFolderRoleAssignmentsCount-1; $i -ge 0; $i--)
            {
                 $folder.RoleAssignments.Remove($i)
            }

            # Save changes
            $folder.Update()
        }
    
        # Set permissions
        $errorInfo = $NULL
        if ($securityItems -ne $NULL)
        {
            $folder.BreakRoleInheritance($true)
            foreach ($objectName in $securityItems.Keys)
            {
                $roleTypeName = $securityItems[$objectName]
                try
                {
                    $roleDefinition = $web.RoleDefinitions.GetByType($roleTypeName)
                }
                catch
                {
                    $errorInfo += $objectName + "; "
                    continue
                }
                if ($web.SiteGroups[$objectName] -ne $NULL)
                {
                    $customRoleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($web.SiteGroups[$objectName])
                }
                else
                {
                    $customRoleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($objectName,$null,$null,$null)
                }
                $customRoleAssignment.RoleDefinitionBindings.Add($roleDefinition)
                $folder.RoleAssignments.Add($customRoleAssignment)
            }

            # Save changes
            $folder.Update()
        }
        return $errorInfo
    }
}
Remove-PSSession -Session $session

# If there was an error when changing permissions, show the error
if ($errorInfo -ne $NULL)
{
    $Context.LogMessage("Failed to set folder permissions for " + $result + " because the specified Role Type was not found on the server.", "Warning")
}

Script 2: SharePoint Online

Parameters:

  • $webApplicationURL - Specifies the URL of the SharePoint web application.
  • $folderPath - Specifies the path to the folder for which to update the access permissions.
    Note: You can use value references (e.g. %name%) to use properties of the object on which the script is executed as a part of the folder path. For example, if you specify Shared Documents/Folder A/%name% and execute the script on a user whose name is John Doe, the resulting path will be Shared Documents/Folder A/John Doe.
  • $stopInheritablePermissions - Specifies whether to stop inheriting permissions from the parent folder.
  • $customSecurityItems - Specifies the permissions to set.
    You can specify custom security settings for users, Active Directory groups or SharePoint groups. Format:

    "MyUser@company.com"="RoleType";"ADgroupName"="RoleType";"SharePointGroupName"="RoleType"

    Default role types: Administrator, Contributor, Reader, WebDesigner.
Edit Remove
PowerShell
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")

$webApplicationURL = "https://company.sharepoint.com/sites/MySite" # TODO: modify me
$folderPath = "Shared Documents/Folder A/%name%" # TODO: modify me

$stopInheritablePermissions = $False # TODO: Specify $False if the folder inherits permissions from the parent folder

$customSecurityItems = @{"MySharepointGroup"="Administrator"; "MyAdGroup" = "Reader"; "MyUser@company.com"="Reader"} # TODO: Specify custom security for users (other than the target user), groups, and SharePoint groups
# "User or AD Group name"="RoleType";"SharePointGroupName"="RoleType"
# Default role types: Administrator, Contributor, Reader, WebDesigner.
# Specify $customSecurityItems = $NULL for default (inherited) permissions

# Connect to SharePoint Online
$office365Cred = $Context.GetOffice365Credential()
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($office365Cred.Username, (ConvertTo-SecureString $office365Cred.GetNetworkCredential().Password -AsPlainText -Force))
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($webApplicationURL)
$clientContext.Credentials = $credentials
$web = $clientContext.Web

# Get user folder
$folderUrl = "$webApplicationURL/$folderPath"
$folder = $web.GetFolderByServerRelativeUrl($folderUrl)
$clientContext.Load($folder)

try
{
    $clientContext.ExecuteQuery()
}
catch
{
    $folder = $NULL
}

if ($folder -eq $NULL)
{
    $Context.LogMessage("Folder does not exist", "Error")
    return
}


if ($stopInheritablePermissions)
{
    $folder.ListItemAllFields.BreakRoleInheritance($False, $False)
}
else
{
    $folder.ListItemAllFields.ResetRoleInheritance()
}
$clientContext.ExecuteQuery()

# Set custom permissions
if ($customSecurityItems -ne $NULL)
{
    $folder.ListItemAllFields.BreakRoleInheritance($True, $False)
    foreach ($objectName in $customSecurityItems.Keys)
    {
        $roleTypeName = $customSecurityItems[$objectName]
        try
        {
            $roleDefinition = $web.RoleDefinitions.GetByType($roleTypeName)
        }
        catch
        {
            $Context.LogMessage($_.Exception.Message, "Warning")
            continue
        }
    
        $trustee = $web.SiteGroups.GetByName($objectName)
        $clientContext.Load($trustee)
        try
        {
            $clientContext.ExecuteQuery()
                
        }
        catch
        {
            $trustee = $NULL
        }
            
        if ($trustee -eq $NULL)
        {
            $trustee = $web.EnsureUser($objectName)
            $clientContext.Load($trustee)
    
            try
            {
                $clientContext.ExecuteQuery()
            }
            catch
            {
                $Context.LogMessage("Trustee '$objectName' not found", "Warning")
                continue
            }
        }
    
        $roleDefinitionBinding = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($clientContext)
        $roleDefinitionBinding.Add($roleDefinition)
        $result = $folder.ListItemAllFields.RoleAssignments.Add($trustee, $roleDefinitionBinding)
    }
        
    # Save changes
    $clientContext.ExecuteQuery()
}


Comments ( 2 )
avatar
Frank
September 21, 2019

How about sharepoint online ? Any easy way to adapt this ?

avatar
Support
September 25, 2019

Hello,

We added a script for SharePOint Online. It can be executed in Business Rules, Custom Commands and Scheduled tasks configured for the User object type.

Leave a comment