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

PowerShell脚本创建文件夹并设权限:首次运行权限不生效问题

PowerShell脚本首次设置文件夹权限失效问题解决

问题根源

首次运行脚本时权限不生效,主要有两个核心原因:

  1. 文件夹刚创建后,直接调用Get-Acl可能获取到未同步的ACL缓存,后续修改操作基于旧的ACL状态执行,无法正确写入新权限规则。
  2. 原脚本中FileSystemAccessRule缺少继承和传播参数,权限规则的应用范围不明确,系统无法正确解析并落地规则。

修复后的脚本

$desired_install_loc = ${env:ProgramFiles}

$base_path = Join-Path $desired_install_loc 'Base_Test'
$install_path = Join-Path $base_path 'Install_Test'

function Create-Directory {
    $baseDir = if (!(Test-Path $base_path)) {
        New-Item -ItemType Directory -Force -Path $base_path
    } else {
        Get-Item -Path $base_path
    }

    $installDir = if (!(Test-Path $install_path)) {
        New-Item -ItemType Directory -Force -Path $install_path
    } else {
        Get-Item -Path $install_path
    }

    return $baseDir, $installDir
}

function Replace-FolderPerms($folder) {
    $acl = $folder.GetAccessControl()
    $add_rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
        "BUILTIN\Users",
        "Read",
        "ContainerInherit,ObjectInherit",
        "None",
        "Allow"
    )

    $acl.SetAccessRuleProtection($true, $true)
    $acl.AddAccessRule($add_rule)

    $folder.SetAccessControl($acl)
}

$baseDir, $installDir = Create-Directory
Replace-FolderPerms $baseDir
Replace-FolderPerms $installDir

关键修改说明

  • 直接操作文件夹对象:创建文件夹时获取New-Item返回的实例,避免通过Get-Acl读取缓存数据,确保基于最新的文件夹状态修改权限。
  • 完善权限规则参数:给FileSystemAccessRule补充继承(ContainerInherit,ObjectInherit)和传播(None)参数,明确权限应用到文件夹及其子对象。
  • 改用对象原生方法:调用文件夹对象的GetAccessControl和SetAccessControl方法,比单独使用Set-Acl更可靠,减少文件系统延迟或锁定导致的写入失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:25:25