Skip to main content

PowerShell function to set ACL folder permissions.

Function SetFolderPermissions
{
  <#
  .SYNOPSIS
    Function SetFolderPermissions is an advanced function which can set NTFSpermissions on a specified folder.

  .DESCRIPTION
    Function SetFolderPermissions is an advanced function which can set NTFSpermissions on a specified folder.

  .PARAMETER FolderPath
    Indicates the path to the folder whose permissions are being modified.
    This path must exist.

  .PARAMETER Grantee
    Indicates the user or group to which permissions are being granted.
    This user or group must exist.

  .PARAMETER Perms
    Indicates the ACL permissions that will be assigned to the user or group specified in $Grantee (comma-delimited).
    Possible ACL permissions are:
    *AppendData
    *ChangePermissions
    *CreateDirectories
    *CreateFiles
    *Delete
    *DeleteSubdirectoriesAndFiles
    *ExecuteFile
    *FullControl
    *ListDirectory
    *Modify
    *Read
    *ReadAndExecute
    *ReadAttributes
    *ReadData
    *ReadExtendedAttributes
    *ReadPermissions
    *Synchronize
    *TakeOwnership
    *Traverse
    *Write
    *WriteAttributes
    *WriteData
    *WriteExtendedAttributes

  .EXAMPLE
    SetFolderPermissions "E:\logs\Applogs" "IIS_IUSRS" "FullControl"
    SetFolderPermissions "E:\logs\LogFiles" "IIS_IUSRS" "FullControl"
    SetFolderPermissions "E:\logs\FailedReqLogFiles" "IIS_IUSRS" "FullControl"
    SetFolderPermissions "E:\Applications" "IIS_IUSRS" "ReadAndExecute"
#>
  [CmdletBinding()]
  Param
  (
    [Parameter(Mandatory = $true, Position = 1)]
    [String] $FolderPath,

    [Parameter(Mandatory = $true, Position = 2)]
    [String]$Grantee,

    [Parameter(Mandatory = $true, Position = 3)]
    [String]$Perms
  )

  # Verify that the specified path exists. Exit script if it does not.
  if (!(Test-Path "$FolderPath"))
  {
    Write-Host -ForegroundColor red "Error setting folder permissions. Path, $FolderPath, does not exist."
    break
  }

  $Acl = Get-Acl $FolderPath

  ForEach ($perm in $Perms.split("{,}"))
  {
    if ($perm -ne "FullControl")
    {
      $perm = "$perm, Synchronize"
    }

    $AclRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Grantee, $Perm, "ContainerInherit, ObjectInherit", "None", "Allow")
    $Acl.SetAccessRule($AclRule)
  }

  # Commit the new permissions
  Set-Acl $FolderPath $Acl
}