Update folder permissions for multiple folders at once using powershell - OnTheKnows/A GitHub Wiki

Define the root folder path

$rootFolderPath = "D:\Users" # Update with your specific root folder path

Define folders to exclude from modification

$excludeFolders = @("_Disabled", "_Orphaned") # Add folder names to exclude from modification

Get all subfolders in the root folder

$subfolders = Get-ChildItem -Path $rootFolderPath -Directory

Loop through each subfolder

foreach ($folder in $subfolders) { # Get the folder name $folderName = $folder.Name

# Check if the folder should be excluded
if ($excludeFolders -contains $folderName) {
    Write-Host "Folder '$folderName' is excluded from modification."
    continue  # Skip to the next folder if excluded
}

# Construct the user or group name (assuming folder names are user names)
$userName = $folderName

Check if the user or group exists

$existingUser = Get-ADUser -Filter "SamAccountName -eq '$userName'" -ErrorAction SilentlyContinue
if ($existingUser -ne $null) {
    # Get the folder path
    $folderPath = $folder.FullName

    # Disable inheritance and remove existing inherited permissions
    $acl = Get-Acl $folderPath
    $acl.SetAccessRuleProtection($true, $true)
    #$acl.Access | Where-Object { $_.IsInherited -eq $true } | ForEach-Object { $acl.RemoveAccessRule($_) }
    Set-Acl -Path $folderPath -AclObject $acl

    # Add permission for the user to the folder
    $permission = "$userName","FullControl","ContainerInherit,Objectinherit","Inheritonly","Allow"
    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
    $acl.AddAccessRule($rule)
    Set-Acl -Path $folderPath -AclObject $acl

    Write-Host "Permissions updated for folder '$folderName'."
}
else {
    Write-Host "User '$userName' not found. Permissions not updated for folder '$folderName'."
}

}