Your script is currently removing existing ACL entries and replacing them with new ones, instead of adding the new entries to the existing ones.
The script should ensure that the permissions set on a parent folder are inherited by all its subfolders and files.
function Set-ACLRecursive {
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[System.IO.DirectoryInfo]$Folder
)
# Get the folder name
$FolderName = $Folder.Name
# Build the name of the groups
$ReadGroupName = "L.$FolderName_Read"
$WriteGroupName = "L.$FolderName_Write"
# Check if groups exist in AD and get their SID
$ReadGroup = Get-ADGroup -Filter { Name -eq $ReadGroupName } -ErrorAction SilentlyContinue
$WriteGroup = Get-ADGroup -Filter { Name -eq $WriteGroupName } -ErrorAction SilentlyContinue
if ($ReadGroup -and $WriteGroup) {
$ReadGroupSID = $ReadGroup.SID
$WriteGroupSID = $WriteGroup.SID
# Get current ACL
$ACL = Get-Acl -Path $Folder.FullName
# Create ACL rules
$ReadRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
$ReadGroupSID, "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow")
$WriteRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
$WriteGroupSID, "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
# Add ACL rules to ACL object
$ACL.AddAccessRule($ReadRule)
$ACL.AddAccessRule($WriteRule)
# Apply the modified ACL to the folder
Set-Acl -Path $Folder.FullName -AclObject $ACL
} else {
Write-Warning "One or both groups ($ReadGroupName, $WriteGroupName) do not exist in AD."
}
# Set ACL permissions for sub-folders recursively
foreach ($SubFolder in $Folder.GetDirectories()) {
Set-ACLRecursive $SubFolder
}
}
# Path Root folder
$RootFolder = "C:\path\to\folder"
# Function call to start scanning
Set-ACLRecursive (Get-Item $RootFolder)
Before attempting to add ACL entries, the script now checks if the groups actually exist in Active Directory. This avoids errors if the groups are missing.
Instead of setting the ACL object's protection and removing all existing rules, the script now adds new access rules to the existing ACL object. This ensures that existing permissions are preserved.
The ContainerInherit,ObjectInherit
flags on the FileSystemAccessRule
objects ensure that the permissions are inherited by subfolders and files.