使用 Powershell 修改 ACL 后无法访问文件夹

Cannot access folder after modifying ACL with Powershell

我正在尝试使用以下代码通过 Powershell 修改文件夹 ACL。首先我想清除 ACL 并停止继承,然后只向其中添加特定用户。

这似乎工作正常,但如果我试图打开该文件夹,它会出现以下错误。

脚本有什么问题?

$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"

您正在设置一个空的 ACL,然后在您不再拥有权限时尝试进行更改。通常,您应该在第二个 Set-ACL

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

相反,尝试只设置一次 ACL:

$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

如果您需要保留现有权限,请改用 $acl.SetAccessRuleProtection($True, $True)

最后,确保您在测试对文件夹的访问时确实以 DBUSERADMIN 身份登录。