Ádám Nagy
Ádám Nagy

Reputation: 15

How to remove all access rules from folder AND all subfolders using PowerShell?

I know this question was answered for a specific folder, but I would like to remove a user from all subfolders as well.

I tried to set the inheritance and propagation values to make sure the setting is inherited, but it still only applies for the root directory, no matter how I set the arguments. (part of) my code looks like this:

$inherit = "ContainerInherit, ObjectInherit"
$propagation = "None"
$Acl=get-acl $o2
$Accessrule = New-Object system.security.AccessControl.FileSystemAccessRule($o1,"Read", $inherit, $propagation,"Allow")
$Acl.RemoveAccessRuleAll($Accessrule)
Set-Acl -Path $o2 -AclObject $Acl

Upvotes: 1

Views: 6783

Answers (1)

Micky Balladelli
Micky Balladelli

Reputation: 9991

Careful with the following, it will remove ACLs

TEST BEFORE USING

I will strongly recommend making a ROBOCOPY with the full ACLs on a separate drive before using the following. If something is not right, you can always copy the files or the ACLs or both back.

Ok here is something you can start with. Like Ansgar says, you pretty much loop through, the folder list, and for each folder you retrieve all Access Controls Entry (ACE) in each ACL.

If the ACE is not inherited, you remove it.

Updated to use $o1 Ok in this version the ACE needs to be assigned to the user defined by $o1.

I have not tested it, so make some tests and check the values step by step before unleashing hell.

$filepath = "<your drive letter>:"

$folders = @((get-item $filePath))
$folders += Get-ChildItem $filePath -Recurse | where { $_.PSIsContainer -ne $false }

Foreach ($folder in $folders)
{

    $acl = Get-Acl -Path $folder.FullName

    Foreach($access in $acl.access) 
    { 
        if ($access.isinherited -eq $false -and $access.IdentityReference.Value -eq $o1)
        { 
            $acl.RemoveAccessRule($access) 
        }  
    } 
    Set-Acl -path $folder.fullname -aclObject $acl 
}

Upvotes: 1

Related Questions