使用PowerShell在文件夹结构中获取目录用户(Get-ACL),有没有更简单的方法?

时间:2019-02-07 08:33:11

标签: powershell

此脚本用于查找对文件夹结构内的文件夹具有任何显式权限的特定用户,这很好!但是,是否有一种更简便的方法来列出文件夹路径和$ _。Access.IdentityReference.Value,而无需循环输入?或者,实际上可以吗?

$foldStruct = get-childitem "C:\temp" -recurse -Attributes D | get-acl 
ForEach ($fold in $foldStruct) {
    ForEach ($perm in $fold.Access.IdentityReference) {
        ForEach ($user in $perm.Value) {            
            If ($user -like "Dom\A*" -or $user -like "Dom\B*") {
                    Write-Host $user
                    Write-Host $fold.Path
            }  
        }                  
    }   
}

2 个答案:

答案 0 :(得分:0)

IS 更简单是有争议的。

  • PowerShell的另一种方法是将对象作为输出。
  • 我将使用基于RegEx的-like来代替两个-match
  • 嵌套的ForEach可以替换为Where-Object和Select-Object
  • 路径将包含Microsoft.PowerShell.Core\FileSystem::,我将使用-split '::'将其删除。

## Q:\Test\2019\02\07\SO_54569198.ps1
$Base = "C:\temp" 
# to use a -match instead of -like anchor at begin and escape the \ => \\ 
$Users = "^Dom\\A|^Dom\\B"   

$folderACLs = Get-ChildItem $Base -Recurse -Directory | Get-Acl |
   Where-Object {$_.Access.IdentityReference.Value -match $Users } |
      Select-Object @{n='User';e={($_.Access.IdentityReference.Value|?{$_ -match $Users})}},
                    @{n='Path';e={($_.Path -split '::')[1] }}

输出可能/将在该列中包含多个用户,所以要分开它们:

ForEach($folderACL in $folderACLs){
    ForEach($User in ($folderACL.User){
        [PSCustomObject]@{
            User = $User
            Path = ($_.folderACL.Path -split '::')[1] 
        }
    }
}

答案 1 :(得分:0)

我在思考与LotPings相同的地方,使用正则表达式-match过滤用户,而不是两次-like

我想到了这个

$users = '^Dom\\[AB].*'  # regex to find usernames beginning with 'A' or 'B'

$subfolders = Get-ChildItem -Path "C:\Temp" -Recurse -Directory
foreach ($folder in $subfolders) {
    $folder | Get-Acl | ForEach-Object { $_.Access  } | 
        Where-Object {$_.IdentityReference.Value -match $users} | ForEach-Object {
        [PSCustomObject]@{
            'Folder'            = $folder.FullName
            'User'              = $_.IdentityReference
            # add extra info about access type for this user if you like
            # 'AccessControlType' = $_.AccessControlType
            # 'IsInherited'       = $_.IsInherited
            # 'InheritanceFlags'  = $_.InheritanceFlags
            # 'PropagationFlags'  = $_.PropagationFlags
        }
    }
}