且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Powershell递归设置文件夹权限?

更新时间:2022-11-28 11:38:23

使用 SetAccessRuleProtection() 禁用继承并删除继承的ACE:

  $ acl.SetAccessRuleProtection($ true,$ false)

使用 RemoveAccessRule() 删除现有的(非继承的)ACE:

  $ acl。访问| ForEach对象{$ acl.RemoveAccessRule($ _)|空值} 

使用 AddAccessRule() 来添加新的ACE:

  $ ace = New-Object Security.AccessControl.FileSystemAccessRule user,... 
$ acl.AddAccessRule( $ ace)
...

仅对最顶层的文件夹执行此操作。在下面的所有地方均启用继承功能,因此您的更改会自动传播。


I have a directory which I want to go through recursively and set permissions on all the folders. So the order of operations should be:

  1. Remove all ACL from folder
  2. Add ACL to folder
  3. Set ACL

I tried the below code, but I am getting the error

Cannot set the ACL because the method that it needs to invoke, SetSecurityDescriptor, does not exist.

foreach ($folder in Get-ChildItem -Path c:\perms -Recurse -Directory) {
    $AccessRule = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("user", "FullControl", "ContainerInherit,ObjectInherit", "InheritOnly", "Allow")
    $acl = Get-Acl $folder
    $acl.SetAcccessRule($AccessRule)
    Set-Acl -Path $folder.FullName -AclObject $acl
}

I got rid of the error message, and it added the ACL, but I want to basically remove all ACLs from the folder and add new ones.

I updated my script to look like this:

$acl = Get-Acl -Path "c:\perms"
$acl.SetAccessRuleProtection($true,$false)
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) | Out-Null }
$ace = New-Object System.Security.Accesscontrol.FileSystemAccessRule ("user", "FullControl", "ContainerInherit,ObjectInherit", "InheritOnly", "Allow")
$acl.AddAccessRule($ace)
Set-Acl -Path "c:\perms" -AclObject $acl

If I want to add multiple $ace, is it just a matter of declaring $ace2, $ace3 and then calling $acl.AddAccessRule($ace2), $acl.AddAccessRule($ace3).

Use SetAccessRuleProtection() to disable inheritance and remove inherited ACEs:

$acl.SetAccessRuleProtection($true, $false)

Use RemoveAccessRule() to remove existing (non-inherited) ACEs:

$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) | Out-Null }

Use AddAccessRule() to add new ACEs:

$ace = New-Object Security.AccessControl.FileSystemAccessRule "user", ...
$acl.AddAccessRule($ace)
...

Do this only for the topmost folder. Leave inheritance enabled everywhere below, so your changes are propagated automatically.