Remove ACL Question

Hello All,

I’m a big fan of this site and despite having some frustrating troubles as of late with a script I just wrote the other day, I’m excited to be posting here!

I’m trying to remove all permissions on all files and folders within a specific directory structure, and the script I created has given me mixed results and I do not know why. At this point, I run the code below and what has been happening most of the time is that each file and folder that the script iterates through, localizes all of the files and folders permissions(as intended), prepared for removal. However, the “Set-ACL” portion of the script to actually remove the permissions - at times - will work without any issues, work with mostly all files and folders, but not all, or simply not at all. The most common occurrence, lately, out of the 3 of the aforementioned results, is the latter: I localize all files and folders permissions, but none of them are removed-- no clue why. Below is the code I’m working with-- any advice or direction would be greatly appreciated! Thanks!

Invoke-Command -ComputerName NYC-FILER -ScriptBlock {

#Remove all ACLs from a network share, subdirectories, & files
$Array=@()
 $TopLevelFolder="Z:\SHARED\Marketing\RIA Channel - Copy"  
  $Dirs=(gci $TopLevelFolder -Recurse).fullname | Sort-Object -Descending
 $Array+=$Dirs 
#$Array+=$TopLevelFolder

    Foreach($Dir in $Array) {
     
          $Acl=Get-Acl $Dir
           #Use the .SetAccessRuleProtection() method to turn off inheritance.  
            #Set the first parameter to "$True" to block inheritance.
             #Set the second parameter to "$True" to copy the formerly inherited rules to the local level to remove all access.
            $ACL.SetAccessRuleProtection($True,$True)
           $Acl.access | Foreach { $Acl.RemoveAccessRule($_) } 
          Set-Acl -Path $Dir -AclObject $Acl    

    }


}

UPDATE: I decided to go a different route and replaced my last line of Set-ACL with CACLS and I got everything I needed. I will check back to confirm once I test one or two more times. Below is the revised code.

Invoke-Command -ComputerName NYC-FILER -ScriptBlock {

#Remove all ACLs from a network share, subdirectories, & files
$Array=@()
$TopLevelFolder="Z:\SHARED\Marketing\RIA Channel - Copy"  
$Dirs=(gci $TopLevelFolder -Recurse).fullname | Sort-Object -Descending
$Array+=$Dirs 
#$Array+=$TopLevelFolder

Foreach($Dir in $Array) {
 
      $Acl=Get-Acl $Dir
      #Use the .SetAccessRuleProtection() method to turn off inheritance.  
      #Set the first parameter to "$True" to block inheritance.
      #Set the second parameter to "$True" to copy the formerly inherited rules to the local level to remove all access.
      $ACL.SetAccessRuleProtection($True,$True)
      $Acl.access | Foreach { CMD /C CACLS $Dir /E /R $_.IdentityReference }    

}

}

You could try the code proposed here: [url]Delete permissions on a folder. This seems to work fine for me.