Evaluating AD Group Membership

This code will eventually be part of a script that will evaluate if a users (provided via text file) are a part of selection of groups in an OU. If they are, they are to be removed. For now I am just testing and ack if they are. I have included the snippet here.

$OU = "OU=Level2,OU=Level1,OU=Application,OU=Group,DC=Domain,DC=NET"
$Groups = (Get-ADGroup -Filter * -SearchBase $OU  -Properties *).Name
$Users = Get-Content ".\users.txt"

Foreach ($User in $Users) {
    Write-Host "$User"
    ForEach ($Group in $Groups) {
        $grpMembers = Get-ADGroupMember -Identity $Group | Select -ExpandProperty DistinguishedName

        If ($grpMembers -Contains $User) {
            Write-Host "    Member of $Group"
        else {
            <# Action when all if and elseif conditions are false #>

    Write-host " "

Essentially, what this code will do is simply output the name of each user; then output the group name if the user is a member. I am getting no group name outputted. I am using a select few uses that I know are members of most of these groups; however no group output. Any help is appreciated.

Have you tried:


If I got it right you may start with something like this:

$OU = 'OU=Level2,OU=Level1,OU=Application,OU=Group,DC=Domain,DC=NET'
$UserList = Get-Content -Path .\users.txt

foreach ($UserName in $UserList) {
    $GroupList = 
    Get-ADPrincipalGroupMembership -Identity $UserName 
    foreach ($Group in $GroupList) {
            UserName = $UserName
            Group    = $Group.Name
            Member   = if ($Group.DistinguishedName -notmatch $([REGEX]::Escape($OU))) { $true }Else { $false }

Now you have the data you need to do further actions. :wink:

The output is returning all domain groups the user is a member of.

Hmmm … depending on your AD structure and on the OU you provide it should output some groups the users are member of and some groups they are not.