Search code examples
powershellacl

How to remove ntfs permission of a specific user on a directory with powershell?


This script tries to do the following

  • create SHARE, disable inheritance and convert inherited rules to explicits rules.
  • remove any rights from BUILTIN\Utilisateurs on this directory

Unfortunately, at the end, the rights remains the same, and Utilisateurs is still in the rules !

What am I doing wrong ?

$sharePath = "C:\SHARE"

New-Item -Path $sharePath -ItemType Directory
$acl = Get-Acl -Path $sharePath
$acl.SetAccessRuleProtection($true, $true)
Set-Acl -Path $sharePath -AclObject $acl

Write-Host "Before :"
$acl.Access | Format-List *

$groupToRemove = "BUILTIN\Utilisateurs"
foreach ($accessRule in $acl.Access) {
    if ($accessRule.IdentityReference -eq $groupToRemove) {
        # Delete the rule. It seems to work because it returns true in powershell
        $acl.RemoveAccessRule($accessRule)
    }
}

Set-Acl -Path $sharePath -AclObject $acl

Write-Host "After :"
$acl.Access | Format-List *

Solution

  • Solved, you need to get the acl again after disabling inheritance

    $sharePath = "C:\SHARE"
    
    New-Item -Path $sharePath -ItemType Directory
    $acl = Get-Acl -Path $sharePath
    $acl.SetAccessRuleProtection($true, $true)
    Set-Acl -Path $sharePath -AclObject $acl
    
    # NEED TO GET THE ACL AGAIN
    $acl = Get-Acl -Path $sharePath
    
    Write-Host "Before :"
    $acl.Access | Format-List *
    
    $groupToRemove = "BUILTIN\Utilisateurs"
    foreach ($accessRule in $acl.Access) {
        if ($accessRule.IdentityReference -eq $groupToRemove) {
            # Delete the rule. It seems to work because it returns true in powershell
            $acl.RemoveAccessRule($accessRule)
        }
    }
    
    Set-Acl -Path $sharePath -AclObject $acl
    
    Write-Host "After :"
    $acl.Access | Format-List *