PowerShell查询AD安全组权限的路径处理及功能优化问题
PowerShell 权限查询脚本问题解决方案
问题1:支持传入无引号带空格路径
解决方法
PowerShell 默认会将无引号的空格分隔内容识别为独立参数,给参数添加ValueFromRemainingArguments特性捕获所有剩余输入,自动拼接为完整路径即可:
function Get-Permissions { [Parameter(ValueFromRemainingArguments=$true)] [string[]]$folderParts $folder = $folderParts -join ' ' (Get-Acl $folder).Access | Where-Object { $_.IdentityReference -like "ABC\*" -and $_.IdentityReference -notlike "*FILE_SUPPORT*" -and $_.IdentityReference -notlike "*PRINT*" } | Select-Object -Property IdentityReference }
修改后可直接执行Get-Permissions C:\My Drive\My Stuff\My Files无需加引号。
问题2:从文件批量读取路径传递给Get-Acl
解决方法
手动给路径加引号的操作会将引号本身识别为路径内容,导致Get-Acl找不到路径,直接读取每行路径传递即可:
# 直接传递给Get-Acl Get-Content "$home\$user\appfiles\out.txt" | ForEach-Object { Get-Acl $_ } # 传递给自定义的Get-Permissions函数写法同理 Get-Content "$home\$user\appfiles\out.txt" | ForEach-Object { Get-Permissions $_ }
问题3:遍历路径所有上级目录查询权限
解决方法
通过循环调用Split-Path -Parent逐层获取上级目录,直到到达根目录停止,每一层查询权限后按要求格式输出:
function Get-HierarchyPermissions { param( [string]$InputPath ) $currentPath = $InputPath # 循环直到到达根目录 while ($currentPath -ne '' -and $currentPath -ne (Split-Path $currentPath -Qualifier)) { # 输出当前层级路径 Write-Output $currentPath # 查询当前路径权限 $perms = Get-Permissions $currentPath # 输出对应权限组 $perms | ForEach-Object { $groupName = $_.IdentityReference -replace '^ABC\\','' Write-Output "-$groupName" } # 切换到上级目录 $currentPath = Split-Path $currentPath -Parent } } # 批量调用示例 Get-Content "$home\$user\appfiles\out.txt" | ForEach-Object { Get-HierarchyPermissions $_ }
问题4:去掉安全组名称的ABC\域名前缀
解决方法
之前的写法未正确转义正则中的反斜杠,也未匹配域名后的分隔符,调整正则表达式即可:
# 直接替换字符串 $groupName = $_.IdentityReference.Value -replace '^ABC\\', '' # 如果要在Select-Object中直接生成自定义属性 Select-Object @{ Name = 'Security Group' Expression = { $_.IdentityReference.Value -replace '^ABC\\', '' } }
正则中^匹配字符串开头,\\是转义后的反斜杠,只会替换前缀的ABC\部分,不会影响组名内部的字符。
内容的提问来源于stack exchange,提问作者JSallo
相关产品推荐
相关产品推荐

