You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Powershell为禁用权限继承的文件夹批量添加用户权限

PowerShell批量设置禁用继承的文件夹权限脚本

你之前的脚本存在两个核心错误:

  • 未初始化$acl变量就直接调用$acl.SetAccessRule(),属于变量未定义错误
  • 最后将子文件夹的ACL直接设置到根目录,逻辑完全颠倒,应该给每个关闭继承的子文件夹单独添加权限规则

可用完整脚本

# 基础配置项,可根据实际情况修改
$targetRoot = "D:\Economy"
$targetUser = "MYCOMPANY\firstname.surname"
$grantPermission = "Modify"

# 构造权限规则,添加继承参数确保权限可以向下传递
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
    $targetUser,
    $grantPermission,
    [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit,
    [System.Security.AccessControl.PropagationFlags]::None,
    [System.Security.AccessControl.AccessControlType]::Allow
)

# 先更新根目录权限
$rootAcl = Get-Acl -Path $targetRoot
$rootAcl.SetAccessRule($accessRule)
Set-Acl -Path $targetRoot -AclObject $rootAcl

# 遍历所有子文件夹,给关闭了继承的目录单独添加权限
Get-ChildItem -Path $targetRoot -Directory -Recurse | ForEach-Object {
    $folderPath = $_.FullName
    $currentAcl = Get-Acl -Path $folderPath
    # 仅处理禁用了权限继承的文件夹
    if ($currentAcl.AreAccessRulesProtected) {
        $currentAcl.SetAccessRule($accessRule)
        Set-Acl -Path $folderPath -AclObject $currentAcl
        Write-Host "已更新权限:$folderPath"
    }
}

注意事项

  • 运行脚本前建议先执行以下命令确认需要修改的文件夹范围,避免误操作:
    Get-ChildItem -Path "D:\Economy" -Directory -Recurse | Where-Object {(Get-Acl $_.FullName).AreAccessRulesProtected} | Select-Object FullName
    
  • 脚本只会新增指定用户的权限,不会修改原有权限规则,也不会更改文件夹的继承开关配置
  • 建议先使用测试目录验证脚本逻辑,确认符合预期后再在生产环境执行

内容的提问来源于stack exchange,提问作者naikon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:54:07