使用 Powershell 递归设置文件夹权限?
Recursively set permissions on folders using Powershell?
我有一个目录,我想递归地访问它并设置所有文件夹的权限。所以操作顺序应该是:
- 从文件夹中删除所有 ACL
- 将 ACL 添加到文件夹
- 设置访问控制列表
我尝试了下面的代码,但我收到了错误
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
}
我摆脱了错误消息,它添加了 ACL,但我想基本上从文件夹中删除所有 ACL 并添加新的。
我将脚本更新为如下所示:
$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
如果我想添加多个$ace
,是不是只要声明$ace2
、$ace3
然后调用$acl.AddAccessRule($ace2)
、$acl.AddAccessRule($ace3)
就可以了。
使用 SetAccessRuleProtection()
禁用继承并删除继承的 ACE:
$acl.SetAccessRuleProtection($true, $false)
使用 RemoveAccessRule()
删除现有的(非继承的)ACE:
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) | Out-Null }
使用AddAccessRule()
添加新的ACE:
$ace = New-Object Security.AccessControl.FileSystemAccessRule "user", ...
$acl.AddAccessRule($ace)
...
只对最顶层的文件夹执行此操作。在下方各处启用继承,以便自动传播您的更改。
我有一个目录,我想递归地访问它并设置所有文件夹的权限。所以操作顺序应该是:
- 从文件夹中删除所有 ACL
- 将 ACL 添加到文件夹
- 设置访问控制列表
我尝试了下面的代码,但我收到了错误
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
}
我摆脱了错误消息,它添加了 ACL,但我想基本上从文件夹中删除所有 ACL 并添加新的。
我将脚本更新为如下所示:
$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
如果我想添加多个$ace
,是不是只要声明$ace2
、$ace3
然后调用$acl.AddAccessRule($ace2)
、$acl.AddAccessRule($ace3)
就可以了。
使用 SetAccessRuleProtection()
禁用继承并删除继承的 ACE:
$acl.SetAccessRuleProtection($true, $false)
使用 RemoveAccessRule()
删除现有的(非继承的)ACE:
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) | Out-Null }
使用AddAccessRule()
添加新的ACE:
$ace = New-Object Security.AccessControl.FileSystemAccessRule "user", ...
$acl.AddAccessRule($ace)
...
只对最顶层的文件夹执行此操作。在下方各处启用继承,以便自动传播您的更改。