Powershell: Remove Inheritance, cloning the ACl and then removing a specific rule

This block of code was used to remove inheritance from all folders in the $RootFolder and Copy the current Permissions that were previously inherited.  Then it reloads the ACL to allow the Domain Users rule to be removed.  If you do not remove and save the inheritance first, the ACL will not remove the individual rule.

$RootFolder - "C:\Temp\"
cd $RootFolder

# Get list of Folders where Inheritance is enabled
$Folders = Get-ChildItem $RootFolder | ?{ $_.PSIsContainer } | ? {!(Get-Acl $_.FullName).AreAccessRulesProtected}

# Loop through Each Folder
ForEach ($Folder in $Folders)
{
    Echo $Folder

    # You must disable inheritance before you can remove
    # one of the rules from the ACL
    # Get ACL for current Folder

    $SourceACL = Get-ACL -Path $Folder
    echo "------====== BEFORE ======---------"
    echo $SourceACL.Access
    $SourceACL.SetAccessRuleProtection($True, $True)
    Set-Acl -Path $Folder -AclObject $SourceACL

    $SourceACL = Get-ACL -Path $Folder
    $rules =  $SourceACL.Access | Where-Object {($_.IdentityReference -like "DOMAIN\Domain Users")}
    #echo "------====== RULES ======---------"
    #echo $rules

    ForEach ($rule in $rules)
    {
       # echo "------====== RULE ======---------"
       # echo $rule

        $SourceACL.RemoveAccessRuleSpecific($rule)
    }
    echo "------====== AFTER ======---------"
    echo $SourceACL.Access

    #Removes the inheritance but copies existing ACE's

    Set-Acl -Path $Folder -AclObject $SourceACL
}

Comments

Popular posts from this blog

Setting up a new Exchange 2013 DAG

Error setting Out of Office via Outlook during Exchange 2010/2013 Coexistence