【问题标题】:Script Won't Set Permissions with Wildcard脚本不会使用通配符设置权限
【发布时间】:2015-11-11 13:06:33
【问题描述】:

我编写了一个 PowerShell 脚本,用于在共享目录的 4000 多个文件夹中创建子文件夹“Admin”(如果尚不存在)。创建子文件夹后,我需要子文件夹的权限仅适用于域中的特定组。我没有收到任何错误,除了子文件夹上的文件夹已经存在错误,但我让脚本运行了 12 个小时,但它从未完成。我停止了脚本,发现所有 Admin 子文件夹都已创建,但没有设置权限。

如果我取出$folder 中的* 通配符,添加一个文件夹名称,它可以完美运行。如何使用* 通配符使其无需手动输入超过 4000 个文件夹名称?

这是我的脚本:

# If the folder for Equipment Images does not exist, make a new one and set the correct permissions.
$Location = "E:\Images\Equipment\*\"
$file = "E:\Images\Equipment\*\Admin"
foreach ($_ in (Get-ChildItem E:\Images\Equipment\*\)) {
    if (($_.PSIsContainer -AND $_.name -eq "Admin")-eq $false) {
        New-Item -Path $location -Name "Admin" -ItemType directory
        $errorActionPreference = "continue"
    }
    $folder = "E:\Images\Equipment\*\Admin"
    $acl = Get-Acl $folder
    if ($acl.AreAccessRulesProtected) {
        $acl.Access | % {$acl.purgeaccessrules($_.IdentityReference)}
    } else {
        $isProtected = $true 
        $preserveInheritance = $false
        $acl.SetAccessRuleProtection($isProtected, $preserveInheritance) 
    }
    $account = "recoequip\folder sales group"
    $rights = [System.Security.AccessControl.FileSystemRights]::FullControl
    $inheritance = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit"
    $propagation = [System.Security.AccessControl.PropagationFlags]::None
    $allowdeny = [System.Security.AccessControl.AccessControlType]::Allow

    $dirACE = New-Object System.Security.AccessControl.FileSystemAccessRule ($account,$rights,$inheritance,$propagation,$allowdeny)
    $ACL.AddAccessRule($dirACE)

    Set-Acl -aclobject $ACL -Path $folder
    Write-Host $folder Permissions added
}

【问题讨论】:

  • (这和SQL Server有什么关系?)
  • 我在 sql server 2008 r2 上运行脚本。
  • 我不关注。这是一个 .ps1 文件?您如何“在 SQL Server 上运行它”?即使您是从 SQL Server 代理作业或其他东西运行它,我认为问题与 SQL Server 没有任何关系。无论您从哪里运行脚本,您都可能必须解决通配符问题。
  • 这个问题与sql server没有任何关系,我只是尽可能多地添加信息。我将删除标签。

标签: powershell wildcard acl


【解决方案1】:

不要将通配符与任何 Acl cmdlet 一起使用,我认为这不会起作用。

之前在循环中设置单个文件夹的权限,或者如果以后必须这样做,只需遍历所有文件夹并逐个设置所有admin文件夹的权限。

一些提示:

从 400 个文件夹的一小部分开始进行测试,然后将当前处理的文件夹写入主机,以便您查看进度。

代码示例:

Get-ChildItem E:\Images\Equipment\ -Directory -Filter "admin" -Recurse | ForEach-Object {

  $acl = Get-Acl $_.FullName
   ... # do your permission stuff

}

【讨论】:

  • 你是说把*去掉,把文件夹名1一1吗?
  • @SaraBagford - 不,我是说遍历所有目录以查找所有admin 文件夹并为每个文件夹设置权限。我在答案中添加了一些代码。
  • 我同意循环遍历 Get-ChildItem 的结果并修改每个单独项目的 ACL 的建议,但是如果有更深层次的名为“admin”的文件夹,使用过滤器递归可能会产生不希望的结果在层次结构中。 Get-ChildItem 'E:\Images\Equipment\*\Admin' -Directory | ForEach-Object ... 应该足够了。
  • @PeterHahndorf - 你就是那个男人。谢谢你的代码完美运行。
猜你喜欢
  • 2011-03-14
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-10
  • 2015-11-18
  • 2019-11-23
相关资源
最近更新 更多