How to loop through Active Directory group members in Powershell

spassen picture spassen · Sep 10, 2012 · Viewed 8.8k times · Source

I am trying to make a list of all groups that contain members from a specific OU. To do this, I am reading a file with the list of all group names and using get-ADGroupMember $groupName to find the members of each group. I am converting the value of each member to string and comparing to $member.indexOf("specific OU"). The problem is, I haven't figured out how to get $member[$i].indexOf("specific OU"). My code is below.

EDIT: If I use a for-each loop I can loop through the members properly, but I cannot use the break, which prevents duplicates.

Import-Module ActiveDirectory
#declaring end result group array
$results = @()

#sets path for files
$pathName = $MyInvocation.MyCommand.Path
$pathLen = $pathName.LastIndexOf("\")
$pathStr = $PathName.Substring(0,$pathLen +1)
$APgroupFile = $pathStr + "APGroups.csv"
$groupFile = $pathStr + "GGroups.csv"

#gets the list of group names and loops through them
get-content $groupFile | foreach-object{
#sets all of the group names
#start of if1 
if($_.IndexOf("CN=") -ge 0){
$nameStart = $_.IndexOf("CN=")+3
$nameEnd = $_.indexOf(",")-$nameStart
$name = $_.substring($nameStart, $nameEnd)

#issue starts here
#goal is to find member of "specific OU".
#If found, add group to $results.  If not, go to next group
$members = get-ADGroupMember -Identity $name
if($members.length -gt 0){
$i=0
for($i=0; $i -le ($members.length -1); $i++){
#need to check users OU for specific OU.  If a user is member, save group to .txt.  If none are members, move to next group
    $OU = $members.toString()
    if($OU.indexOf("OU=specific OU") -ge 0){#start of if OU
    $results += New-Object psObject -Property @{'GroupName'=$name; 'Member'=$OU}
    break
    }#end if OU
    }#end for mem.length
}#end if mem.length
}#end if1
}#end foreach

$results | Export-Csv $APgroupFile -NoTypeInformation

Answer

Shay Levy picture Shay Levy · Sep 10, 2012

Try this:

Get-ADGroupMember -Identity $name |
Where-Object {$_.distinguishedName -like '*OU=specific OU*'}