递归AD-Group查询powershell

时间:2014-06-25 14:44:35

标签: .net powershell recursion scripting active-directory

我目前正在开发一个脚本,该脚本将以递归方式获取某个ADGroup所在的ADGroups,并且我希望在树上上下两种方式进行。记住,我不必关心会员资格,只想要团体。我有两个单独的脚本来实现这一点。但是,为了简单起见,我想将2合并为一个脚本,唯一的问题是当我将它们组合起来时它不会运行。我觉得我搞砸了,所以下面是我的代码:

import-module ActiveDirectory
$ServerpathInput = read-host "Please enter the domain for which you would like to query for AD groups For example:domain.com"
New-PSDrive -Name Domain2 -PSProvider ActiveDirectory -Root "DC=domain, DC=com" -Server $ServerpathInput -Credential domain\username
cd Domain2:
$GroupName = $GroupName2 = read-Host "Enter a AD group to query"
$GroupName = $GroupName2
Function GetADGroupRecursive ($GroupName, $GroupName2) {
    $array = Get-ADGroup -Identity $GroupName -Properties Members 
    $array2 = Get-ADGroup -Identity $GroupName2 -Properties memberof
    Foreach ($item in $array, $array2)
    {
        $string = $item.Members.Value.remove(0, $item.Members.Value.IndexOf("=")+1) 
        $string2 = $item.memberof.Value.remove(0, $item.Memberof.Value.IndexOf("=")+1)
        $ReturnedName = $string.Remove($String.IndexOf(","))
        $ReturnedName2 = $string2.Remove($String2.IndexOf(","))        
        Write-Host $ReturnedName
        Write-Host $ReturnedName2        
        $GroupName = $ReturnedName
        $GroupName2 = $ReturnedName2
    }
    If (!$GroupName,!$GroupName2)    #Prevents infinite loop by exiting the loop if the variable is not populated, otherwise it loops with populated variable.
      {break}
      Else {
          GetADGroupRecursive $GroupName, $GroupName2
      }
}
GetADGroupRecursive $GroupName, $GroupName2               #Calls function

正如你所看到的,它有点混乱。我不确定如何继续,或者这可以更容易地完成。我已经研究并发现了很多递归脚本来查询用户成员资格,但不是用于组。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)