Monday, June 28, 2021

Transfer Sitecore security settings with Powershell

Sitecore security settings

You can set security on each item in Sitecore for any number of roles (or users, but you shouldn't do that). A while ago I had to set the security for a particular role in a way that I actually changed a few dozen items. This was on a pre-production environment and related to a new site that was prepared in that environment. That new site is moved to the production environment with a package, and that will include the security settings on all the items in the site. But what with all the ones that are not in the site and that are also touched by adding a new security rule for this role? I couldn't move all those items and I don't want to do it manually...  so I came up with a script in Powershell. I'm posting it here for my future reference, but maybe someone else can use it as well...

Sitecore Powershell Extensions (SPE) to the rescue

I created a script that created a Powershell script. Executing the created script will set all the security rules that were found for a particular role in a give path.

function GetAssignedItems($path)
{
    Write-Host "Start: " $path
     
    $items = Get-ChildItem -Path $path -Recurse
    $rootItem = Get-Item -Path $path
    $items = $items + $rootItem
 
    foreach ($item in $items)
    {
        $acl = Get-ItemAcl -Identity "MYROLE" -Item $item
        if ($acl)
        {
            foreach ($rule in $acl)
            {
                "Add-ItemAcl -PropagationType " + $rule.PropagationType + " -SecurityPermission " + $rule.SecurityPermission + " -AccessRight '" + $rule.AccessRight +"' -Identity 'MYROLE' -Path '"+ $item.Paths.FullPath + "'"
            }
        }
    }
    Write-Host "Done."
}
 
GetAssignedItems "/sitecore/media library"

Just replace "myrole" with the name of your role and that's it. The call to the function takes the root you want to check.

This will generate output like this:
Add-ItemAcl -PropagationType Entity -SecurityPermission AllowAccess -AccessRight 'item:read' -Identity 'MYROLE' -Path '/sitecore/media library/Project'
Add-ItemAcl -PropagationType Entity -SecurityPermission DenyInheritance -AccessRight '*' -Identity 'MYROLE' -Path '/sitecore/media library/Project'

You can do this for any database - just note that the database is not added to the result output. 

This actually exports the rights - meaning it will generate a script that is able to set them again on any other environment. 

To import the rights into an environment, run the resulting script in a Powershell console in your Sitecore admin. This will set the security as required. Just make sure you run the script in the correct database ;)


No comments:

Post a Comment