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

PowerShell批量修改ACL权限仅文件夹生效文件报错求助

问题根源

  • PowerShell 中单引号包裹的字符串不会解析内部变量,你代码中写的 '$item' 会被系统直接识别为字面量路径「$item」,自然找不到对应文件,触发路径不存在报错
  • 执行 Select-Object -Property fullname 后,$item 是包含 FullName 属性的自定义对象,不是纯路径字符串,需要显式调用属性才能拿到正确路径
  • Get-Acl 执行失败返回空值后,后续调用 $existingAcl.SetAccessRule($rule) 就会触发空值调用方法的报错
  • 末尾 Set-Acl 路径用了单引号包裹 '$ITEM',也存在相同的变量解析问题

修正后可用脚本

# 直接获取遍历到的所有文件/文件夹对象,不需要提前筛选属性,避免后续取值错误
$items = Get-ChildItem \\file.location.com.au\project\people\user1 -Recurse

foreach ($item in $items) {
    # 直接传入对象的FullName属性作为路径,无需多余引号包裹
    $existingAcl = Get-Acl -Path $item.FullName

    $permissions = 'SERVER\USER1', 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'
    $rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions

    $existingAcl.SetAccessRule($rule)
    $existingAcl | Set-Acl -Path $item.FullName
}

可选优化说明

如果需要区分处理文件或文件夹,可以在 Get-ChildItem 后追加对应参数:

  • 仅处理文件:追加 -File 参数
  • 仅处理文件夹:追加 -Directory 参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:06:02