Roger Wayne
Roger Wayne

Reputation: 429

Cannot access folder after modifying ACL with Powershell

I am trying to modify folder ACL through Powershell with following code. First i want to clear ACL and stop inheritance and then add only specific users to it.

This seem working fine, but if i trying to open that folder it gives following error.

What is wrong with the script?

$acl = Get-ACL -Path "c:\mydata"
$acl.SetAccessRuleProtection($True, $False)
$acl | Set-Acl -Path "c:\mydata"
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("DBUSER","FullControl","ContainerInherit,ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("ADMIN","FullControl","ContainerInherit,ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
$acl | Set-Acl -Path "c:\mydata"

enter image description here

Upvotes: 1

Views: 698

Answers (1)

Cpt.Whale
Cpt.Whale

Reputation: 5341

You are setting an empty ACL, then trying to make changes when you no longer have permissions. Normally, you should be getting an error on the second Set-ACL

$acl | Set-Acl $path
Set-Acl : The process does not possess the 'SeSecurityPrivilege' privilege which is required for this operation.

Instead, try setting the ACL only once:

$path = 'c:\mydata'
$acl = Get-ACL $path

$rule1 = [System.Security.AccessControl.FileSystemAccessRule]::new(
    "DBUSER","FullControl","ContainerInherit,ObjectInherit","None","Allow" )
$rule2 = [System.Security.AccessControl.FileSystemAccessRule]::new(
    "ADMIN","FullControl","ContainerInherit,ObjectInherit","None","Allow" )

$acl.AddAccessRule($rule1)
$acl.AddAccessRule($rule2)

# Flush the inherited permissions, and protect your new rules from overwriting by inheritance
$acl.SetAccessRuleProtection($True, $False)

# Output what the new access rules actually look like:
$acl.Access | ft

$acl | Set-Acl $path

If you need to keep the existing permissions, then use $acl.SetAccessRuleProtection($True, $True) instead.

Finally, make sure you're actually logged in as either DBUSER or ADMIN when testing access to the folder.

Upvotes: 2

Related Questions