问题描述
我有一个问题,需要例如在 Active Directory 中使用 powershell 获取属于某个组的所有组,以此类推。
因此,如果您的 A 组有 B,B 组有 C,那么我需要这些组的名称,包括 A。
如果 C 也有 A 我不希望它进入无限循环,那么如何解决以下问题。
这是我目前的代码。
$groupname = "a","b","c"
foreach($grouphp in groupname)
{
$groupname += (get-adgroupmember -server $domain -identity $grouphp | where-object {$_.objectclass -like "group"}).name
}
这会将它们添加到 $groupname 1 级别,如果未找到组,并且如果找到的组也是我正在查找的组,它将多次列出它们。
感谢任何帮助。
解决方法
您可以创建一个列表来跟踪,然后仅添加之前未添加的列表。
$groupname = "a","b","c"
$grouplist = New-Object System.Collections.Generic.List[string]
foreach($group in $groupname)
{
if($group -notin $grouplist){$grouplist.Add($group)}
Get-ADGroupMember -server $domain -Identity $group |
Where-Object objectclass -like "group" | ForEach-Object {
if($_.name -notin $grouplist){$grouplist.Add($_.name)}
}
}
$grouplist
,
请使用以下脚本从嵌套组中获取用户:
https://gallery.technet.microsoft.com/Get-nested-group-15f725f2