Public/Tasks/Invoke-FilePermissionsTask.ps1

#Requires -Modules SitecoreInstallFramework
Set-StrictMode -Version Latest

Write-Verbose "Loading $($MyInvocation.MyCommand.Path)"


function Invoke-FilePermissionsTask {
    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Path,
        [psobject[]]$Rights
    )

    <#
        Rights should contains
        @{
            User
            FileSystemRights
            AccessControlType
 
            InheritanceFlags
            PropagationFlags
        }
    #>


    # We need to get/set/get as permissions may be in a
    # non-canonical format: https://serverfault.com/a/287702

    if (!$WhatIfPreference) {
        Get-Acl -Path $Path | Set-Acl -Path $Path
    }

    $acl = Get-Acl -Path $Path

    foreach ($entry in $Rights) {
        $user = $entry.User
        $permissions = $entry.FileSystemRights
        $control = 'Allow'
        if ($entry['AccessControlType']) { $control = $entry.AccessControlType }
        $inherit = 'ContainerInherit', 'ObjectInherit'
        if ($entry['InheritanceFlags']) { $inherit = $entry.InheritanceFlags }
        $prop = 'None'
        if ($entry['PropagationFlags']) { $prop = $entry.PropagationFlags }

        Write-TaskInfo -Message $user -Tag $control
        Write-TaskInfo -Message $path -Tag 'Path'
        Write-TaskInfo -Message $permissions -Tag 'Rights'
        Write-TaskInfo -Message $inherit -Tag 'Inherit'
        Write-TaskInfo -Message $prop -Tag 'Propagate'

        if ($PSCmdlet.ShouldProcess($Path, "Setting permissions")) {

            if (Test-Path -Path $Path) {
                $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, $permissions, $inherit, $prop, $control)
                $acl.SetAccessRule($rule)

                Write-Verbose "$control '$permissions' for user '$user' on '$path'"
                Write-Verbose "Permission inheritance: $inherit"
                Write-Verbose "Propagation: $prop"
                Set-Acl -Path $Path -AclObject $acl
                Write-Verbose "Permissions set"
            }
            else {
                throw "Path '$Path' does not exist."
            }
        }
    }
}

Register-SitecoreInstallExtension -Command Invoke-FilePermissionsTask.ps1 -As FilePermissions -Type Task -Force
Write-Verbose "Loaded $($MyInvocation.MyCommand.Path)"